From 58408fd68066359c736c991e782eede34e71b36c Mon Sep 17 00:00:00 2001 From: Mayank Kumar Date: Sat, 31 Oct 2026 19:59:40 +0530 Subject: [PATCH] fix: reject off-main-thread stop() before changing session state FrameMonitorImpl.stop() set the state to STOPPED and then called FrameSource.stop(). ChoreographerFrameSource.stop() throws on the wrong thread before it removes its frame callback, so an off-main-thread session.stop() left the session reporting stopped while the callback kept re-posting every vsync. A retry of stop() returned early because the state was no longer STARTED, so the callback could never be removed. stop() now checks the calling thread before any state change. Off the main thread it throws IllegalStateException and leaves the session running, so the caller can still stop it from the main thread. Stopping an idle or stopped session stays a no-op on any thread. Adds regression tests and documents the contract in FramePulseSession, README and docs/FRAME_MONITOR.md. --- README.md | 2 +- docs/FRAME_MONITOR.md | 13 +++++- .../framepulse/api/FramePulseSession.kt | 8 +++- .../framepulse/internal/FrameMonitorImpl.kt | 13 +++--- .../internal/FramePulseSessionImplTest.kt | 41 +++++++++++++++++++ 5 files changed, 69 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ed2238e..5816a28 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ class MainActivity : ComponentActivity() { # Threading and lifecycle -- **Main-thread-confined.** Call `FramePulse.start()` and `session.stop()` on the main thread; `start()` throws `IllegalStateException` otherwise. FramePulse is not thread-safe and uses no locks. +- **Main-thread-confined.** Call `FramePulse.start()` and `session.stop()` on the main thread; both throw `IllegalStateException` otherwise. A rejected `stop()` leaves the session running, so you can still stop it from the main thread. FramePulse is not thread-safe and uses no locks. - **The listener runs on the main thread**, synchronously inside the frame callback. Keep it cheap. `FrameMetrics` is immutable, so you can hand it to another thread. - **You own the lifecycle.** FramePulse does not observe Activity or process lifecycle. Every `start()` needs a matching `stop()`. Calling `stop()` more than once is fine, and you can call it from inside the listener. - **No restart.** A stopped session stays stopped; call `FramePulse.start()` again for a new one. diff --git a/docs/FRAME_MONITOR.md b/docs/FRAME_MONITOR.md index b4baaef..1a612db 100644 --- a/docs/FRAME_MONITOR.md +++ b/docs/FRAME_MONITOR.md @@ -485,7 +485,7 @@ Reference implementation: `com.mayank.framepulse.internal.FrameMonitorImpl`. |------|----------------| | `MonitorState` lifecycle (`IDLE` → `STARTED` → `STOPPED`) | FPS math (`FPSCalculator`) | | Forwarding `FrameSource` ticks to an injected consumer while `STARTED` | Listener dispatch (`FramePulseSessionImpl`) | -| Main-thread check on `start()` (injectable for JVM tests) | Direct `Choreographer` registration | +| Main-thread check on `start()` and `stop()` (injectable for JVM tests) | Direct `Choreographer` registration | ### Lifecycle @@ -517,6 +517,17 @@ If registration throws an `Exception`: Only `Exception` is caught — not `Error` subclasses such as `OutOfMemoryError`, which should propagate without lifecycle recovery attempts. +### Thread check on stop + +`FrameMonitorImpl.stop()` checks the calling thread **before** changing state. It returns early +when not `STARTED`, so stopping an idle or stopped monitor stays a no-op on any thread. When +`STARTED` and called off the main thread, it throws `IllegalStateException` and leaves the +monitor `STARTED` with the source still registered. + +The order matters. `ChoreographerFrameSource.stop()` throws on the wrong thread before it +removes its callback. If the monitor moved to `STOPPED` first, a retry of `stop()` would return +early and the callback would keep re-posting every vsync for the life of the process. + ### Metrics wiring (v0.1) `FramePulseSessionImpl` builds the monitor with a frame consumer. Each tick goes to diff --git a/framepulse/src/main/java/com/mayank/framepulse/api/FramePulseSession.kt b/framepulse/src/main/java/com/mayank/framepulse/api/FramePulseSession.kt index d352a1b..91058e2 100644 --- a/framepulse/src/main/java/com/mayank/framepulse/api/FramePulseSession.kt +++ b/framepulse/src/main/java/com/mayank/framepulse/api/FramePulseSession.kt @@ -16,7 +16,13 @@ package com.mayank.framepulse.api */ interface FramePulseSession { - /** Stops monitoring and prevents further listener invocations. */ + /** + * Stops monitoring and prevents further listener invocations. Idempotent. + * + * Main thread only. On a running session, a call from another thread throws + * [IllegalStateException] and changes nothing: the session keeps running, so it can still be + * stopped from the main thread. On a session that is not running, this is a no-op on any thread. + */ fun stop() /** Whether the session is actively receiving frame signals. */ diff --git a/framepulse/src/main/java/com/mayank/framepulse/internal/FrameMonitorImpl.kt b/framepulse/src/main/java/com/mayank/framepulse/internal/FrameMonitorImpl.kt index eaef66f..5aa3ba7 100644 --- a/framepulse/src/main/java/com/mayank/framepulse/internal/FrameMonitorImpl.kt +++ b/framepulse/src/main/java/com/mayank/framepulse/internal/FrameMonitorImpl.kt @@ -12,8 +12,8 @@ import com.mayank.framepulse.internal.source.FrameSource * Owns the [FrameSource] lifecycle and forwards each `frameTimeNanos` to [frameConsumer] while * started. * - * Threading: main-thread-confined and not thread-safe. [start] checks the calling thread; - * [stop] and frame delivery are expected on the same thread. No locks are used. + * Threading: main-thread-confined and not thread-safe. [start] and [stop] check the calling + * thread; frame delivery is expected on the same thread. No locks are used. * * Design details (lifecycle, threading): `docs/FRAME_MONITOR.md`. * @@ -32,7 +32,7 @@ internal class FrameMonitorImpl( get() = state == MonitorState.STARTED override fun start(config: FramePulseConfig) { - assertMainThread() + assertMainThread("start") requireIdleForStart() state = MonitorState.STARTED @@ -48,6 +48,9 @@ internal class FrameMonitorImpl( override fun stop() { if (state != MonitorState.STARTED) return + // Check before changing state. If the source threw after the state change, the monitor + // would report stopped while the source kept re-posting its frame callback. + assertMainThread("stop") state = MonitorState.STOPPED frameSource.stop() @@ -70,9 +73,9 @@ internal class FrameMonitorImpl( } } - private fun assertMainThread() { + private fun assertMainThread(method: String) { if (!isMainThread()) { - throw IllegalStateException("FrameMonitor.start() must be called from the main thread") + throw IllegalStateException("FrameMonitor.$method() must be called from the main thread") } } diff --git a/framepulse/src/test/java/com/mayank/framepulse/internal/FramePulseSessionImplTest.kt b/framepulse/src/test/java/com/mayank/framepulse/internal/FramePulseSessionImplTest.kt index 23e34e6..16d0f8f 100644 --- a/framepulse/src/test/java/com/mayank/framepulse/internal/FramePulseSessionImplTest.kt +++ b/framepulse/src/test/java/com/mayank/framepulse/internal/FramePulseSessionImplTest.kt @@ -132,6 +132,47 @@ class FramePulseSessionImplTest { assertFalse(session.isRunning) } + @Test + fun stopOffTheMainThreadThrowsAndLeavesTheSessionRunning() { + val session = newSession() + session.start() + source.emit(0L) + + onMainThread = false + assertThrows(IllegalStateException::class.java) { session.stop() } + + // Nothing changed: the source is still registered and frames still reach the listener. + assertTrue(session.isRunning) + assertEquals(0, source.stopCount) + source.emit(PERIOD) + assertEquals(1, received.size) + + // A retry on the main thread stops the source exactly once. + onMainThread = true + session.stop() + + assertFalse(session.isRunning) + assertEquals(1, source.stopCount) + } + + @Test + fun stopOffTheMainThreadIsANoOpWhenNotRunning() { + val idle = newSession() + onMainThread = false + idle.stop() + assertEquals(0, source.stopCount) + + onMainThread = true + val stopped = newSession() + stopped.start() + stopped.stop() + onMainThread = false + stopped.stop() + + assertFalse(stopped.isRunning) + assertEquals(1, source.stopCount) + } + @Test fun sourceStartFailureIsRethrownAndLeavesSessionIdle() { val failure = IllegalStateException("boom")