Skip to content

Commit a5d3cf6

Browse files
romtsnclaude
andauthored
fix(android): Don't block the main thread on the frame metrics looper (#6500)
* fix(android): Don't block the main thread on the frame metrics looper SentryFrameMetricsCollector waited on HandlerThread.getLooper() at the first startCollection(), blocking Activity.onCreate for hundreds of ms on a busy device. Create the handler in onLooperPrepared() instead, and start the thread at init when frames tracking will use it, so its looper is ready before the first frame. Fixes #6443 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog * fix(android): Read the current frame metrics window once per check trackCurrentWindow() now also runs on the HandlerThread in onLooperPrepared(). Reading the volatile currentWindow twice could NPE if onActivityStopped nulled it in between, killing the thread before Looper.loop() and silently stopping frame metrics. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 530623e commit a5d3cf6

5 files changed

Lines changed: 125 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
- Session Replay: Fix `SentryOkHttpInterceptor` hanging forever on responses whose body has no known length, such as Server-Sent Events or a gzipped response, when network details are enabled for the URL ([#6231](https://github.com/getsentry/sentry-java/pull/6231))
2626
- Session Replay: `SentryOkHttpInterceptor` now captures network request and response details only while Session Replay is recording or buffering ([#6486](https://github.com/getsentry/sentry-java/pull/6486))
2727
- Stop marking an OkHttp call span as failed when a connection attempt to one of the host's addresses fails but OkHttp connects on another ([#6472](https://github.com/getsentry/sentry-java/pull/6472))
28+
- Stop blocking the main thread while the frame metrics thread starts when the first activity transaction begins ([#6500](https://github.com/getsentry/sentry-java/pull/6500))
29+
- On a busy device during cold start this could stall the launcher activity's `onCreate` for hundreds of milliseconds.
2830

2931
### Dependencies
3032

‎sentry-android-core/src/main/java/io/sentry/android/core/SpanFrameMetricsCollector.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ public SpanFrameMetricsCollector(
7474
this.frameMetricsCollector = frameMetricsCollector;
7575

7676
enabled = options.isEnablePerformanceV2() && options.isEnableFramesTracking();
77+
if (enabled && options.isTracingEnabled()) {
78+
// Start the frame metrics thread now, so it's ready before the first activity's first frame.
79+
frameMetricsCollector.prepare();
80+
}
7781
}
7882

7983
@Override

‎sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java‎

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import org.jetbrains.annotations.ApiStatus;
3636
import org.jetbrains.annotations.NotNull;
3737
import org.jetbrains.annotations.Nullable;
38+
import org.jetbrains.annotations.VisibleForTesting;
3839

3940
@ApiStatus.Internal
4041
public final class SentryFrameMetricsCollector implements Application.ActivityLifecycleCallbacks {
@@ -48,8 +49,10 @@ public final class SentryFrameMetricsCollector implements Application.ActivityLi
4849

4950
private final @NotNull ILogger logger;
5051
private volatile @Nullable Handler handler;
52+
private volatile boolean handlerThreadStarted = false;
5153
private final @NotNull AutoClosableReentrantLock handlerLock = new AutoClosableReentrantLock();
52-
private @Nullable WeakReference<Window> currentWindow;
54+
// volatile: read from the HandlerThread in onHandlerReady while set on the main thread
55+
private volatile @Nullable WeakReference<Window> currentWindow;
5356
private final @NotNull Map<String, FrameMetricsCollectorListener> listenerMap =
5457
new ConcurrentHashMap<>();
5558
private boolean isAvailable = false;
@@ -116,8 +119,8 @@ public SentryFrameMetricsCollector(
116119
}
117120
isAvailable = true;
118121

119-
// The frame metrics HandlerThread is started lazily on the first startCollection() call.
120-
// Starting it here would block the main thread on HandlerThread.getLooper() during SDK init.
122+
// The frame metrics HandlerThread is started by prepare() or the first startCollection() call,
123+
// and never waited on: see ensureHandlerThreadStarted().
121124

122125
// We have to register the lifecycle callback, even if no profile is started, otherwise when we
123126
// start a profile, we wouldn't have the current activity and couldn't get the frameMetrics.
@@ -294,34 +297,61 @@ public void onActivityDestroyed(@NotNull Activity activity) {}
294297
}
295298

296299
/**
297-
* Lazily starts the background HandlerThread used to receive frame metrics. Deferred out of the
298-
* constructor because {@link HandlerThread#getLooper()} blocks the caller (the main thread during
299-
* SDK init) until the thread is ready, and the handler is only needed once collection starts.
300+
* Starts the background HandlerThread ahead of the first {@link #startCollection} call, so its
301+
* looper is ready by the time the first frame is drawn. Does not block.
302+
*/
303+
public void prepare() {
304+
if (isAvailable) {
305+
ensureHandlerThreadStarted();
306+
}
307+
}
308+
309+
/**
310+
* Starts the background HandlerThread used to receive frame metrics without waiting for it: the
311+
* handler is created on the new thread in {@link HandlerThread#onLooperPrepared()}. Calling
312+
* {@link HandlerThread#getLooper()} here would block the caller (the main thread) until the new
313+
* thread is scheduled, which takes hundreds of ms on a busy device.
300314
*/
301315
private void ensureHandlerThreadStarted() {
302-
if (handler != null) {
316+
if (handlerThreadStarted) {
303317
return;
304318
}
305319
try (final @NotNull ISentryLifecycleToken ignored = handlerLock.acquire()) {
306-
if (handler == null) {
307-
final HandlerThread handlerThread =
308-
new HandlerThread("io.sentry.android.core.internal.util.SentryFrameMetricsCollector");
309-
handlerThread.setUncaughtExceptionHandler(
310-
(thread, e) -> logger.log(SentryLevel.ERROR, "Error during frames measurements.", e));
311-
handlerThread.start();
312-
handler = new Handler(handlerThread.getLooper());
320+
if (handlerThreadStarted) {
321+
return;
313322
}
323+
handlerThreadStarted = true;
324+
final HandlerThread handlerThread =
325+
new HandlerThread("io.sentry.android.core.internal.util.SentryFrameMetricsCollector") {
326+
@Override
327+
protected void onLooperPrepared() {
328+
onHandlerReady(new Handler(getLooper()));
329+
}
330+
};
331+
handlerThread.setUncaughtExceptionHandler(
332+
(thread, e) -> logger.log(SentryLevel.ERROR, "Error during frames measurements.", e));
333+
handlerThread.start();
314334
}
315335
}
316336

337+
@VisibleForTesting
338+
void onHandlerReady(final @NotNull Handler handler) {
339+
this.handler = handler;
340+
// startCollection() or an activity start may have happened before the handler existed, in
341+
// which case trackCurrentWindow() skipped attaching the listener
342+
trackCurrentWindow();
343+
}
344+
317345
public void stopCollection(final @Nullable String listenerId) {
318346
if (!isAvailable) {
319347
return;
320348
}
321349
if (listenerId != null) {
322350
listenerMap.remove(listenerId);
323351
}
324-
Window window = currentWindow != null ? currentWindow.get() : null;
352+
// read the volatile field once: onActivityStopped may null it concurrently
353+
final @Nullable WeakReference<Window> windowRef = currentWindow;
354+
final @Nullable Window window = windowRef != null ? windowRef.get() : null;
325355
if (window != null && listenerMap.isEmpty()) {
326356
stopTrackingWindow(window);
327357
}
@@ -355,7 +385,9 @@ private void setCurrentWindow(final @NotNull Window window) {
355385

356386
@SuppressLint("NewApi")
357387
private void trackCurrentWindow() {
358-
@Nullable Window window = currentWindow != null ? currentWindow.get() : null;
388+
// read the volatile field once: onActivityStopped may null it concurrently
389+
final @Nullable WeakReference<Window> windowRef = currentWindow;
390+
final @Nullable Window window = windowRef != null ? windowRef.get() : null;
359391
if (window == null || !isAvailable) {
360392
return;
361393
}

‎sentry-android-core/src/test/java/io/sentry/android/core/SpanFrameMetricsCollectorTest.kt‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ class SpanFrameMetricsCollectorTest {
2727
var timeNanos = 0L
2828
var lastKnownChoreographerFrameTimeNanos = 0L
2929

30-
fun getSut(enabled: Boolean = true): SpanFrameMetricsCollector {
30+
fun getSut(
31+
enabled: Boolean = true,
32+
tracesSampleRate: Double? = 1.0,
33+
): SpanFrameMetricsCollector {
3134
whenever(frameMetricsCollector.startCollection(any()))
3235
.thenReturn(UUID.randomUUID().toString())
3336
whenever(frameMetricsCollector.getLastKnownFrameStartTimeNanos()).thenAnswer {
@@ -37,6 +40,7 @@ class SpanFrameMetricsCollectorTest {
3740
options.isEnableFramesTracking = enabled
3841
options.isEnablePerformanceV2 = enabled
3942
options.dateProvider = SentryAndroidDateProvider()
43+
options.tracesSampleRate = tracesSampleRate
4044

4145
return SpanFrameMetricsCollector(options, frameMetricsCollector)
4246
}
@@ -90,6 +94,24 @@ class SpanFrameMetricsCollectorTest {
9094
verify(fixture.frameMetricsCollector, never()).startCollection(any())
9195
}
9296

97+
@Test
98+
fun `When enabled and tracing is enabled, it prepares the frame metrics collector`() {
99+
fixture.getSut()
100+
verify(fixture.frameMetricsCollector).prepare()
101+
}
102+
103+
@Test
104+
fun `When tracing is disabled, it doesn't prepare the frame metrics collector`() {
105+
fixture.getSut(tracesSampleRate = null)
106+
verify(fixture.frameMetricsCollector, never()).prepare()
107+
}
108+
109+
@Test
110+
fun `When disabled, it doesn't prepare the frame metrics collector`() {
111+
fixture.getSut(enabled = false)
112+
verify(fixture.frameMetricsCollector, never()).prepare()
113+
}
114+
93115
@Test
94116
fun `If disabled but a span is launched, it doesn't register a listener`() {
95117
val sut = fixture.getSut(enabled = false)

‎sentry-android-core/src/test/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollectorTest.kt‎

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -83,17 +83,30 @@ class SentryFrameMetricsCollectorTest {
8383
fun getSut(
8484
context: Context,
8585
buildInfoProvider: BuildInfoProvider = buildInfo,
86+
prepare: Boolean = true,
8687
): SentryFrameMetricsCollector {
8788
whenever(activity.window).thenReturn(window)
8889
whenever(activity2.window).thenReturn(window2)
8990
addOnFrameMetricsAvailableListenerCounter = 0
9091
removeOnFrameMetricsAvailableListenerCounter = 0
91-
return SentryFrameMetricsCollector(
92-
context,
93-
options,
94-
buildInfoProvider,
95-
windowFrameMetricsManager,
96-
)
92+
val collector =
93+
SentryFrameMetricsCollector(context, options, buildInfoProvider, windowFrameMetricsManager)
94+
if (prepare) {
95+
collector.prepare()
96+
if (collector.getProperty<Boolean>("handlerThreadStarted")) {
97+
awaitHandler(collector)
98+
}
99+
}
100+
return collector
101+
}
102+
103+
// the handler is created asynchronously on the HandlerThread once its looper is prepared
104+
fun awaitHandler(collector: SentryFrameMetricsCollector) {
105+
val deadline = System.currentTimeMillis() + 5_000
106+
while (collector.getProperty<Handler?>("handler") == null) {
107+
check(System.currentTimeMillis() < deadline) { "frame metrics handler was never created" }
108+
Thread.sleep(1)
109+
}
97110
}
98111
}
99112

@@ -142,12 +155,37 @@ class SentryFrameMetricsCollectorTest {
142155

143156
@Test
144157
fun `handler thread is started lazily on first startCollection`() {
145-
val collector = fixture.getSut(context)
146-
// not started during construction (would block the main thread on getLooper at SDK init)
147-
assertNull(collector.getProperty<Handler?>("handler"))
158+
val collector = fixture.getSut(context, prepare = false)
159+
assertFalse(collector.getProperty<Boolean>("handlerThreadStarted"))
148160

149161
collector.startCollection(mock())
150-
assertNotNull(collector.getProperty<Handler?>("handler"))
162+
assertTrue(collector.getProperty<Boolean>("handlerThreadStarted"))
163+
fixture.awaitHandler(collector)
164+
}
165+
166+
@Test
167+
fun `prepare starts the handler thread before startCollection`() {
168+
val collector = fixture.getSut(context, prepare = false)
169+
170+
collector.prepare()
171+
assertTrue(collector.getProperty<Boolean>("handlerThreadStarted"))
172+
fixture.awaitHandler(collector)
173+
}
174+
175+
@Test
176+
fun `listener is attached once the handler is ready if collection started before it`() {
177+
val collector = fixture.getSut(context, prepare = false)
178+
// pretend the HandlerThread is started but its looper isn't prepared yet
179+
collector.injectForField("handlerThreadStarted", true)
180+
181+
collector.startCollection(mock())
182+
collector.onActivityStarted(fixture.activity)
183+
Shadows.shadowOf(Looper.getMainLooper()).idle()
184+
assertEquals(0, fixture.addOnFrameMetricsAvailableListenerCounter)
185+
186+
collector.onHandlerReady(Handler(Looper.getMainLooper()))
187+
Shadows.shadowOf(Looper.getMainLooper()).idle()
188+
assertEquals(1, fixture.addOnFrameMetricsAvailableListenerCounter)
151189
}
152190

153191
@Test

0 commit comments

Comments
 (0)