Threads, Executors & Thread Pools
KOTLIN › JVM Concurrency
What coroutines run on: thread cost, ExecutorService, pool sizing, and why Future.get blocking drove everything since.
Coroutines multiplex onto thread pools rather than replacing them, so interviewers who have been doing this a while probe the layer underneath. Expect to explain what a thread actually costs, how to size a pool for CPU-bound versus IO-bound work, and why ThreadPoolExecutor queues before it grows, which makes maximumPoolSize dead configuration with an unbounded queue. Strong answers connect the formulas to why Dispatchers.Default caps at the core count and IO at 64, and can trace the line from Future.get blocking through CompletableFuture to coroutines.
What this covers
- A thread costs a reserved stack of roughly 1MB, kernel context switches, and a system call to create
- Thread states: BLOCKED means monitor-lock contention only, so blocking IO shows as RUNNABLE
- Callable exists because Runnable cannot return a value or throw; submitting one gives you a Future
- Future.get() blocks, which is the limitation that drove CompletableFuture, RxJava and coroutines
- newCachedThreadPool creates unbounded threads; newFixedThreadPool has an unbounded queue
- ThreadPoolExecutor queues before growing, so an unbounded queue makes maximumPoolSize unreachable
- Sizing: cores or cores+1 for CPU work, cores x (1 + wait/compute) for IO work, then measure
- thenApply is map and thenCompose is flatMap; a nested CompletableFuture means you picked wrong
- submit() stores a task exception in the Future and loses it silently; execute() surfaces it to the uncaught handler
- Submitting to an executor creates a happens-before edge, so passing data in is safe but sharing between tasks is not
- Android: AsyncTask leaked and silently serialised; HandlerThread for a dedicated message-queue thread; Process.setThreadPriority for real scheduling
- Coroutines multiplex onto pools: a blocking call inside one still occupies a real thread
Study this topic
- Threads, Executors & Thread Pools explained: the guided lesson
- 13 practice quiz questions
- 14 revision flashcards
- Threads, Executors & Thread Pools interview questions and answers