🚀 Enrollments Open for Jetpack Compose Cohort 3 — 4 Weeks of Live Learning to Build Modern Android UIs 💚Join Now
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 ThreadsThread Pool Solution
Creating threads is expensiveThreads are reused
Too many threads = OOMPool size is controlled
No task queuingBuilt-in work queue
Hard to manage lifecycleCentralized 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

  1. Task submitted
  2. If threads < corePoolSize → Create new thread
  3. If threads >= corePoolSize → Add to queue
  4. If queue full AND threads < maxPoolSize → Create new thread
  5. 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

PolicyBehavior
AbortPolicyThrows exception (default)
CallerRunsPolicyRuns task in caller thread
DiscardPolicySilently discards task
DiscardOldestPolicyDiscards 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

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

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

Limited slots available each month