← Back to roadmap

Looper, epoll and Vsync: The Heartbeat of an Android Frame

How the main thread waits, wakes and draws: Handler and MessageQueue, the native Looper sleeping in epoll_wait, the eventfd that wakes it, the input and vsync file descriptors it watches, Choreographer's frame and its five steps, and the sync barrier that lets a frame jump the queue. Read from the AOSP source, with a frame timeline you can break.

  • Android
  • Ink
  • Looper
  • Choreographer
  • Internals
On this page
  1. What you’ll study
  2. The basics
  3. Try it: the frame timeline
  4. The high level
  5. The low level
  6. Checkpoint
  7. Why it helps
  8. The map
  9. Edge cases
  10. Cross questions
  11. Revision: key points
  12. Cheat sheet
  13. Read next
  14. The fine print

What you’ll study

  1. What the main thread does all day: wait for a message, run it, repeat.
  2. How Handler, MessageQueue and Looper fit together, and how a message is queued by time.
  3. Where the thread actually sleeps: the native Looper, epoll_wait and the eventfd that wakes it.
  4. How touch and vsync reach the thread as file descriptors the Looper watches.
  5. Choreographer: one frame, its five steps, and how it skips frames when it starts late.
  6. The sync barrier: how a frame jumps ahead of your messages.

How it connects

Every guide in this series ends up here. A touch sample, a vsync tick and your post { } all arrive the same way: as something the main thread’s Looper wakes up for. A frame is just one more message, with a deadline. When a drawing app lags or a list stutters, the question is always the same: what was this thread doing when the frame was due?

This is guide 3 of the ink series, after why naive drawing feels bad and Canvas, Paint and Path. The next guide follows a touch from the glass to the MotionEvent this thread receives.

Read it at your level

Level Read You should be able to
Student The basics, the timeline Say what the main thread does and why a long task freezes the screen
Fresher + The high level Post work with Handler, run a background Looper, and explain what a frame is
Junior + The low level up to Choreographer Explain MessageQueue.next(), why the thread sleeps without burning CPU, and frame callbacks
Mid + Sync barriers, The map Explain why a frame runs before messages posted earlier, and read a frame in a trace
Senior + Edge cases, cross questions Reason about input batching, skipped frames and the new MessageQueue implementations

The basics

An Android app’s UI runs on one thread, the main thread. That thread runs a loop forever: take the next message, run it, take the next. A tap, a frame, a lifecycle callback and your own post { } are all messages on that loop. Because it is one thread, a message that takes 200 ms holds everything behind it for 200 ms, including the frames that should have been drawn.

You talk to a thread’s loop through a Handler:

private val main = Handler(Looper.getMainLooper())

fun onSaved() {
    main.post { status.text = "Saved" }            // runs on the main thread, after what is already queued
    main.postDelayed({ status.text = "" }, 2_000)  // runs no earlier than 2 s from now
}

Any thread can have its own loop. HandlerThread is a thread with a Looper already running:

val worker = HandlerThread("ink-save").apply { start() }
val saver = Handler(worker.looper)

saver.post { saveStrokes() }   // runs on "ink-save", never on the main thread
// when you are done: worker.quitSafely()

Pass the Looper explicitly. The no-argument Handler() constructor is deprecated: the reference warns that implicitly choosing a Looper “can lead to bugs where operations are silently lost”.

Try it: the frame timeline

200 ms of a drawing app’s main thread, from a small model of the code in this guide. Top to bottom: the vsync ticks, what the Looper runs, what the screen shows at each tick, and every touch sample (darker means it waited longer to be seen).

Interactive frame timeline: change the refresh rate and the work per frame, add a slow task or short posts, and switch the sync barrier off to see frames skipped and touch samples waiting. Needs JavaScript.

Things to try: switch on Slow task and watch the frames behind it skip vsyncs. Raise Work per frame past 16 ms at 60 Hz and the screen repeats every other frame even with nothing else running. Switch to 120 Hz and the same work no longer fits. Add Short posts, then switch the Sync barrier off.

The model is a simplification: it folds the render thread and the compositor into one vsync and runs one frame message per vsync. Real traces have more parts, but the shape is the same.

The high level

Five pieces, from your code down to the kernel:

Piece What it is Where
Handler Puts messages on a queue and runs them when they come out android.os.Handler
Message A unit of work: a target Handler, a time (when), and a Runnable or a what/arg payload android.os.Message
MessageQueue The messages, kept in order of when android.os.MessageQueue
Looper The loop: next(), run, repeat android.os.Looper
Native Looper Sleeps in epoll_wait on a set of file descriptors until something is ready system/core/libutils/Looper.cpp

The native Looper watches three kinds of file descriptor on the main thread:

  1. Its own wake-up eventfd. Written whenever a message arrives that should run sooner than the thread planned to wake.
  2. The input channel. A socket from the system’s input dispatcher, carrying touch and key events for this window.
  3. The vsync receiver. A descriptor that becomes readable when the display’s next vsync arrives, once Choreographer has asked for one.

When none of them is ready and no message is due, the thread sleeps in the kernel and costs no CPU. That is why an idle app doesn’t drain the battery while its main thread “runs forever”.

The low level

All excerpts are from AOSP main unless noted, trimmed with …. Links are in The map below.

1. The loop: Looper.loop()

public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    …
    for (;;) {
        if (!loopOnce(me, ident, thresholdOverride)) {
            return;
        }
    }
}

private static boolean loopOnce(final Looper me, …) {
    Message msg = me.mQueue.next(); // might block
    …
}

next() either returns the next message that is due, or blocks until there is one. loopOnce() then calls msg.target.dispatchMessage(msg), which runs your Runnable or handleMessage(). If a Printer was set with setMessageLogging(), it logs ">>>>> Dispatching to …" before and "<<<<< Finished to …" after each message, which is how simple jank detectors measure slow messages.

2. Queuing by time: MessageQueue.enqueueMessage()

The queue is a linked list sorted by when, an uptimeMillis() time. This is the classic version (Android 14’s MessageQueue.java):

if (p == null || when == 0 || when < p.when) {
    // New head, wake up the event queue if blocked.
    msg.next = p;
    mMessages = msg;
    needWake = mBlocked;
} else {
    // Inserted within the middle of the queue.  Usually we don't have to wake
    // up the event queue unless there is a barrier at the head of the queue
    // and the message is the earliest asynchronous message in the queue.
    needWake = mBlocked && p.target == null && msg.isAsynchronous();
    …
}
…
if (needWake) {
    nativeWake(mPtr);
}

A message that becomes the new head while the thread is asleep wakes it; a message further back doesn’t need to, because the thread already plans to wake for the head. postDelayed() simply sets a later when. Because uptimeMillis() “stops when the system enters deep sleep” (SystemClock), a delay is not a wall-clock alarm.

3. Waiting without spinning: MessageQueue.next()

Message next() {
    …
    for (;;) {
        …
        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            …

nativePollOnce() is where the thread sleeps, for as long as the head message is in the future (or forever when the queue is empty). When it returns, next() takes the head if it is due. If the queue is empty or nothing is due yet, it first runs the registered IdleHandlers: “Called when the message queue has run out of messages and will now wait for more. Return true to keep your idle handler active, false to have it removed.”

The msg.target == null check is the sync barrier, covered in section 6.

4. The native Looper: epoll and eventfd

nativePollOnce() goes through JNI (android_os_MessageQueue.cpp) to the native Looper:

mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
…
mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
…
int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

epoll is Linux’s way to wait on many file descriptors at once; eventfd is a counter that behaves like a file. nativeWake() ends up here:

void Looper::wake() {
    …
    uint64_t inc = 1;
    ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));

Writing 1 to the eventfd makes it readable, epoll_wait returns, and the Java loop runs again. Other parts of the system add their own descriptors with Looper::addFd(). The input receiver does (android_view_InputEventReceiver.cpp):

mMessageQueue->getLooper()->addFd(fd, 0, events, this, nullptr);

and so does the vsync side (DisplayEventDispatcher.cpp):

int rc = mLooper->addFd(mReceiver.getFd(), 0, Looper::EVENT_INPUT, this, NULL);

When one of those becomes readable, the native Looper calls its handleEvent() directly, without a Java message: the input receiver reads the events, and the vsync dispatcher calls up into Choreographer.

5. A frame: Choreographer

Choreographer asks for one vsync at a time. When it arrives, onVsync() turns it into a message:

Message msg = Message.obtain(mHandler, this);
msg.setAsynchronous(true);
mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);

That message runs doFrame(), which works through five kinds of callback in a fixed order:

doCallbacks(Choreographer.CALLBACK_INPUT, frameIntervalNanos);

doCallbacks(Choreographer.CALLBACK_ANIMATION, frameIntervalNanos);
doCallbacks(Choreographer.CALLBACK_INSETS_ANIMATION, frameIntervalNanos);

doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameIntervalNanos);

doCallbacks(Choreographer.CALLBACK_COMMIT, frameIntervalNanos);
Step What runs Why it matters for ink
Input The batch of touch samples that arrived since the last frame This is where your onTouchEvent() usually runs
Animation Animators, and your postFrameCallback() callbacks Drive per-frame work here, not with postDelayed(16)
Insets animation Keyboard and system-bar animations
Traversal ViewRootImpl’s measure, layout and draw (recording) Your onDraw() runs here
Commit Bookkeeping after the frame

Input lands in the first step because ViewRootImpl doesn’t handle a batch the moment it arrives. It schedules it for the next frame:

mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
        mConsumedBatchedInputRunnable, null);

unless unbuffered dispatch was requested, in which case it consumes the batch immediately (consumeBatchedInputEvents(-1)). That is the code behind requestUnbufferedDispatch() from guide 1.

Starting late. If the frame message runs well after its vsync because the thread was busy, doFrame() works out how many frames it missed and logs a warning once that reaches a limit:

private static final int SKIPPED_FRAME_WARNING_LIMIT = SystemProperties.getInt(
        "debug.choreographer.skipwarning", 30);
…
Log.i(TAG, "Skipped " + skippedFrames + " frames!  "
        + "The application may be doing too much work on its main "

30 frames is half a second at 60 Hz. Fewer skipped frames are still visible jank; they just aren’t logged.

6. The sync barrier: how a frame jumps the queue

When a view calls invalidate() or requestLayout(), ViewRootImpl.scheduleTraversals() runs:

void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        …
    }
}

A barrier is a message with no target. From the moment it is posted, next() skips every ordinary message behind it and only returns asynchronous ones, which is what the vsync message is. So the frame runs before work you posted after the invalidate, even if that work was due first. When the traversal runs, doTraversal() removes the barrier and your messages flow again. Switch the barrier off in the timeline to see the frame wait its turn instead.

Barriers are framework-only (postSyncBarrier() is hidden from apps), and for good reason: a barrier that is never removed stops every ordinary message on that thread for good.

7. One queue, several implementations

On AOSP main, MessageQueue.java is no longer one file. The android/os folder holds LegacyMessageQueue, LockedMessageQueue, ConcurrentMessageQueue, SemiConcurrentMessageQueue and CombinedMessageQueue, and the build picks one per release:

// Exactly one MessageQueue.java will be added to srcs by messagequeue-gen
…
conditions_default: {
    srcs: ["android/os/LegacyMessageQueue/MessageQueue.java"],
},

The default is the classic linked list shown above; the newer ones rework the queue for less lock contention. The public behaviour (ordering by time, barriers, idle handlers) is the same, which is why this guide quotes the Android 14 file for the classic version.

Checkpoint

You should be able to say:

  • The main thread runs one message at a time; a slow message delays every frame behind it.
  • MessageQueue.next() sleeps in epoll_wait until the head message is due or a descriptor is ready.
  • nativeWake() writes to an eventfd to cut that sleep short.
  • Touch and vsync arrive as file descriptors on the same Looper.
  • A frame runs input, animation, insets, traversal and commit, in that order.
  • A sync barrier lets the asynchronous frame message run before ordinary messages.

Why it helps

Symptom What is happening on the Looper What to do
Ink stutters while a file saves The save is a message on the main thread, and frames wait behind it Move it to a HandlerThread or a coroutine on Dispatchers.IO
“Skipped 40 frames!” in logcat One message ran for 40 vsyncs Find it with a trace, or with the setMessageLogging() detector below
A per-frame effect drifts or stutters It runs on postDelayed(16), not on the frame Use Choreographer.postFrameCallback()
An app is janky only at 120 Hz Work that fit in 16.7 ms doesn’t fit in 8.3 ms Measure frame work against the real refresh rate
“Input dispatching timed out” A touch was not handled within 5 seconds, the input ANR limit Same as above, much worse

Android’s own targets: “your app must render frames in under 16ms to achieve 60 frames per second (fps)”, 11 ms at 90 fps, and frames over 700 ms count as frozen (Slow rendering). An input event not handled “within 5 seconds” is an ANR (ANRs).

Per-frame work, done right:

private val frame = object : Choreographer.FrameCallback {
    override fun doFrame(frameTimeNanos: Long) {
        advanceInkAnimation(frameTimeNanos)       // runs in the animation step of every frame
        Choreographer.getInstance().postFrameCallback(this)
    }
}

fun start() = Choreographer.getInstance().postFrameCallback(frame)
fun stop() = Choreographer.getInstance().removeFrameCallback(frame)

A simple slow-message detector, for debug builds:

var started = 0L
Looper.getMainLooper().setMessageLogging { line ->
    if (line.startsWith(">>>>> Dispatching")) {
        started = SystemClock.uptimeMillis()
    } else if (line.startsWith("<<<<< Finished")) {
        val took = SystemClock.uptimeMillis() - started
        if (took > 16) Log.w("Jank", "Main-thread message took $took ms: $line")
    }
}

Work for when the thread is idle, such as warming a brush texture after the first frame:

Looper.myQueue().addIdleHandler {
    warmUpBrushTextures()
    false // run once; return true to run again at the next idle moment
}

The map

Step Code Where
Post a message Handler.sendMessageAtTime() → MessageQueue.enqueueMessage() Handler.java, Android 14 MessageQueue.java
Wake a sleeping thread nativeWake() → Looper::wake() writes the eventfd android_os_MessageQueue.cpp, Looper.cpp
Loop Looper.loop() → loopOnce() → MessageQueue.next() Looper.java
Sleep nativePollOnce() → Looper::pollInner() → epoll_wait() Looper.cpp
Touch arrives NativeInputEventReceiver::handleEvent() android_view_InputEventReceiver.cpp
Vsync arrives DisplayEventDispatcher::handleEvent() → Choreographer.onVsync() DisplayEventDispatcher.cpp, Choreographer.java
Frame Choreographer.doFrame(), five callback steps Choreographer.java
Barrier and traversal ViewRootImpl.scheduleTraversals(), doTraversal() ViewRootImpl.java
Which queue is built messagequeue-gen core/java/Android.bp

Edge cases

  • Dispatchers.Main is this queue. On Android, coroutines’ main dispatcher posts to the main Looper through a Handler, so a long coroutine step on Main blocks frames exactly like a long post { }.
  • Delays during deep sleep. postDelayed() counts uptimeMillis(), which stops in deep sleep. A 10-minute delay can fire much later in real time. Use AlarmManager or WorkManager for wall-clock timing.
  • Leaked handlers. A Handler subclass that is an inner class holds its Activity; a delayed message keeps both alive until it runs. Remove callbacks in onDestroy(), or post lambdas from a lifecycle-aware scope.
  • Quitting. quit() drops pending messages; quitSafely() runs the ones already due first. The main Looper cannot be quit.
  • Faster displays shrink every budget. The same frame work that fits at 60 Hz can miss every other vsync at 120 Hz. Try it in the timeline.

Cross questions

The main thread "loops forever". Why doesn't it use 100% of a CPU core?

It sleeps in epoll_wait inside the native Looper whenever no message is due and no descriptor is ready. The kernel wakes it when the eventfd, the input channel or the vsync descriptor becomes readable, or when the head message's time arrives.

You post a message, then call invalidate(). Which runs first, the message or the next frame?

Usually the message, if it is already due: it was queued before the barrier. Work posted after the invalidate waits behind the barrier, so the asynchronous frame message runs first.

Why does touch handling run at the start of a frame instead of the moment the event arrives?

ViewRootImpl schedules batched input in Choreographer's input step, so all the samples since the last frame are handled once, just before animation and drawing. With unbuffered dispatch requested, it consumes them immediately instead.

Logcat shows "Skipped 12 frames". Is that a problem?

That log line only appears from 30 skipped frames by default (debug.choreographer.skipwarning). If you see 12, someone lowered the limit; and 12 skipped frames at 60 Hz is a 200 ms freeze either way.

Why should per-frame animation use postFrameCallback() rather than postDelayed(16)?

A frame callback runs in the frame's animation step with the frame's own timestamp, in step with vsync at any refresh rate. A 16 ms delay drifts against vsync, is wrong at 90 or 120 Hz, and can land after the frame it was meant for.

What does nativeWake() actually do?

It writes the value 1 to the native Looper's eventfd. That makes the descriptor readable, so epoll_wait returns and the Java loop checks the queue again.

On a current AOSP checkout you can't find android/os/MessageQueue.java. Where is it?

It is generated: core/java/Android.bp copies one of five implementations (Legacy, Locked, Concurrent, SemiConcurrent, Combined) into place per release, with LegacyMessageQueue as the default.

Revision: key points

  1. One main thread runs one message at a time; frames are messages too.
  2. Handler queues by when (uptimeMillis()); Looper.loop() takes the next due message and runs it.
  3. The thread sleeps in epoll_wait; nativeWake() writes an eventfd to wake it.
  4. Touch and vsync arrive as descriptors on the same native Looper.
  5. A frame runs input, animation, insets animation, traversal and commit.
  6. Batched touch is handled in the next frame’s input step, unless unbuffered dispatch is on.
  7. scheduleTraversals() posts a sync barrier, so the asynchronous frame runs before ordinary messages.
  8. A late frame skips the vsyncs it missed; logcat only reports it from 30 by default.
  9. Budgets: 16 ms at 60 fps, 11 ms at 90; frozen frames over 700 ms; input ANR at 5 s.

Cheat sheet

Each concept in a few words.

Concept In a few words
Main thread Runs one message at a time; frames are messages too.
Looper Takes the next due message from the queue and runs it.
Handler Posts a message with a time to run (when).
epoll_wait Where the idle thread sleeps until something wakes it.
eventfd A counter that is written to wake the sleeping Looper.
Vsync The display’s “next frame” signal; every 16.7 ms at 60 Hz.
Choreographer Runs a frame’s callbacks at each vsync.
Frame steps Input, animation, insets animation, traversal, commit.
Sync barrier Lets the frame run ahead of ordinary messages.
Skipped frame A late frame misses vsyncs; the old picture stays.
Frame budget 16 ms at 60 fps, 11 ms at 90.
Input ANR 5 s without the app finishing an input event.

Search terms that find more: Choreographer doFrame, sync barrier MessageQueue, epoll_wait Looper, nativePollOnce, Perfetto main thread.

The fine print

Excerpts are from AOSP main in November 2026, except MessageQueue.enqueueMessage() and next(), which are from android14-release because main now builds one of several queue implementations. Method names and the callback list change between releases; the shape (one loop, epoll, vsync as an asynchronous message, a barrier for traversals) has been stable for many years. The frame timeline is a model, not a recording.

Part of the ink series: 1. Why naive drawing feels bad, 2. Canvas, Paint and Path.

How useful was this guide?

Only the author sees ratings.

Friday's 5 best, plus one guide

The Friday email is on its way. Until then, follow by RSS.