ThreadPoolExecutor is a powerful class that manages a pool of worker threads, efficiently executing multiple tasks without the overhead of creating new threads for each task.
| Problem with Raw Threads | Thread Pool Solution |
|---|---|
| Creating threads is expensive | Threads are reused |
| Too many threads = OOM | Pool size is controlled |
| No task queuing | Built-in work queue |
| Hard to manage lifecycle | Centralized shutdown |
val executor = ThreadPoolExecutor(
2, // corePoolSize: Minimum threads
4, // maximumPoolSize: Max threads
60L, // keepAliveTime: Idle thread timeout
TimeUnit.SECONDS,
LinkedBlockingQueue<Runnable>(), // Work queue
ThreadFactory { r -> Thread(r, "MyThread") },
ThreadPoolExecutor.AbortPolicy() // Rejection policy
)
// Fixed thread pool
val fixed = Executors.newFixedThreadPool(4)
// Cached thread pool (creates as needed)
val cached = Executors.newCachedThreadPool()
// Single thread executor
val single = Executors.newSingleThreadExecutor()
// Scheduled executor
val scheduled = Executors.newScheduledThreadPool(2)
val executor = Executors.newFixedThreadPool(4)
// Submit tasks
executor.execute {
// Background work
}
val future = executor.submit<String> {
// Return result
"Result"
}
val result = future.get() // Blocks until complete
// Shutdown properly
executor.shutdown()
executor.awaitTermination(5, TimeUnit.SECONDS)
| Policy | Behavior |
|---|---|
| AbortPolicy | Throws exception (default) |
| CallerRunsPolicy | Runs task in caller thread |
| DiscardPolicy | Silently discards task |
| DiscardOldestPolicy | Discards oldest queued task |
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚