androidengineers.Book a session
โ† All interview questions
ThreadIntermediate4 min

What is HandlerThread and when to use it?

Answer

What is HandlerThread?

HandlerThread is a Thread subclass that has its own Looper built-in, making it easy to handle messages and runnables sequentially on a background thread.

Why Use HandlerThread?

Unlike a regular Thread (which executes once and dies), HandlerThread:

  • Stays alive and processes tasks in a queue
  • Guarantees sequential execution of tasks
  • Provides a Looper that you can attach Handlers to
  • Avoids creating new threads repeatedly

Code Example

// Create and start HandlerThread
val handlerThread = HandlerThread("MyBackgroundThread")
handlerThread.start()

// Create Handler attached to HandlerThread's Looper
val backgroundHandler = Handler(handlerThread.looper)

// Post tasks to run on background thread
backgroundHandler.post {
    // This runs on HandlerThread, not UI thread
    val data = fetchDataFromNetwork()
    
    // Switch to UI thread to update UI
    mainHandler.post {
        updateUI(data)
    }
}

// Don't forget to quit when done
handlerThread.quitSafely()

When to Use HandlerThread

Use CaseWhy HandlerThread
Serial background tasksTasks execute one after another
Camera callbacksNeeds dedicated thread with looper
Sensor data processingContinuous stream of events
File I/O operationsSequential reads/writes
Database operations (pre-Room)Ordered transactions

HandlerThread vs Other Options

ApproachBest For
HandlerThreadSequential background tasks needing a Looper
ExecutorServiceParallel task execution
CoroutinesModern async programming (recommended)
WorkManagerGuaranteed background work

Important Points

  • Always call quit() or quitSafely() when done
  • quitSafely() processes pending messages before terminating
  • The Looper is only available after start() is called

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising