Questions
ThreadAdvanced5 min
Explain ThreadPoolExecutor in Android?
ThreadPoolExecutor
Answer
What is ThreadPoolExecutor?
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.
Why Use Thread Pools?
| 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 |
Key Parameters
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 )
How It Works
- Task submitted
- If threads < corePoolSize → Create new thread
- If threads >= corePoolSize → Add to queue
- If queue full AND threads < maxPoolSize → Create new thread
- If queue full AND threads >= maxPoolSize → Reject task
Common Executors (Factory Methods)
// 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)
Usage Example
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)
Rejection Policies
| Policy | Behavior |
|---|---|
| AbortPolicy | Throws exception (default) |
| CallerRunsPolicy | Runs task in caller thread |
| DiscardPolicy | Silently discards task |
| DiscardOldestPolicy | Discards oldest queued task |
Best Practices
- Always shutdown executors when done
- Choose pool size based on task type (CPU vs I/O bound)
- Consider using Coroutines for simpler async code
- Use meaningful thread names for debugging
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚