Quiz: ExecutorService in Java: Thread Pool, Callable and Future

Total: 8 questions

1. 

What is ExecutorService in Java, and why do you need a thread pool?

ExecutorService is an interface in java.util.concurrent that manages a pool of threads and a queue of tasks. You hand a task to the pool with submit() or execute(), a free pool thread runs it, and the result comes back through a Future.

try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
    Future<Integer> future = pool.submit(() -> 2 + 2);
    System.out.println(future.get());   // 4
}                                       // close() waits for the tasks (Java 19+)

A pool exists so you don't create a thread for every task. A platform thread is an OS thread with its own stack: creating and destroying one is expensive, and an unbounded number of threads leads to OutOfMemoryError and a CPU busy with context switches. A pool reuses a few threads, caps the number of tasks running at once (the rest wait in the queue) and lets you stop all the work with one shutdown() call.

2. 

Which pools does the Executors class create, and what is the risk of each?

  • newFixedThreadPool(n) — exactly n threads and an unbounded LinkedBlockingQueue. If tasks arrive faster than they complete, the queue grows until OutOfMemoryError.
  • newCachedThreadPool() — from 0 to Integer.MAX_VALUE threads and a SynchronousQueue that stores no tasks. No free thread means a new one is created, and under a load spike you get thousands of threads. An idle thread lives 60 s.
  • newSingleThreadExecutor() — one thread and an unbounded queue: tasks run strictly in order, but one long task delays all the others.
  • newScheduledThreadPool(n) — delayed and periodic tasks; an exception silently cancels all future runs of a periodic task.
  • newVirtualThreadPerTaskExecutor() (Java 21) — a virtual thread per task, no queue and no limit: you have to limit resources instead, such as the number of database queries.
  • newWorkStealingPool() (Java 8) — a ForkJoinPool sized to the number of cores; the order is not FIFO.

The threads of the first four pools are not daemons, so an unclosed pool keeps the JVM alive. newWorkStealingPool and virtual threads are the opposite: they are daemons, and if main doesn't wait for the tasks, the JVM exits and the tasks are silently lost.

3. 

What is the difference between execute() and submit() in ExecutorService, and where does an exception from the task go?

void execute(Runnable) is declared in the Executor interface and returns nothing. An exception from the task is thrown in the pool thread: the default UncaughtExceptionHandler prints the stack trace, the thread dies, and the pool creates a replacement.

submit() takes a Runnable or a Callable and returns a Future. The exception is stored inside the Future: get() throws ExecutionException, and the original exception is in getCause(). If get() is never called, nobody sees the error — not in the console, not in the logs.

The rule: if you don't need the result, use execute(); if you use submit(), call get() or catch exceptions inside the task itself.

4. 

What is the difference between Callable and Runnable?

  • Runnable — java.lang, Java 1.0, method void run(): no result, and checked exceptions have to be caught inside.
  • Callable<V> — java.util.concurrent, Java 5, method V call() throws Exception: returns a result through Future.get() and may throw checked exceptions, which the caller receives wrapped in ExecutionException.

A Runnable goes to new Thread(…), execute() and submit(); a Callable goes to submit(), invokeAll(), invokeAny(), schedule() or a FutureTask, but not to a Thread constructor.

Which interface a lambda becomes is decided by the compiler from its body. () -> { Thread.sleep(100); } returns nothing and fits only Runnable, so pool.submit(...) with it doesn't compile: “unreported exception java.lang.InterruptedException”. Add return null; and the same lambda becomes a Callable.

5. 

What methods does Future have, and which exceptions does get() throw?

Future<V> is a “receipt” for the result of a task running in another thread.

  • get() blocks until the result is ready. It throws ExecutionException if the task failed (the original exception is in getCause()), CancellationException if the task was cancelled, and InterruptedException if the waiting thread was interrupted.
  • get(timeout, unit) waits no longer than the given time and throws TimeoutException. The task itself keeps running.
  • isDone() — whether the task has finished, without waiting; true on success, on exception and after cancellation alike.
  • cancel(true) — a queued task never starts, and a running one gets interrupt(); whether it stops depends on whether it reacts to interruption. isCancelled() reports the cancellation.
  • Java 19: state() returns RUNNING, SUCCESS, FAILED or CANCELLED; resultNow() and exceptionNow() return the result or the exception without waiting and throw IllegalStateException if the task isn't in the matching state.

The task's actions happen-before the return from get(), so the result you get is visible without volatile or synchronized.

6. 

What is the difference between shutdown(), shutdownNow(), awaitTermination() and close(), and what happens if a pool is never closed?

  • shutdown() — new tasks are rejected (RejectedExecutionException); already submitted ones, including the queue, run to completion. Doesn't wait.
  • shutdownNow() — additionally calls interrupt() on running tasks and returns the list of queued tasks that will never start. Doesn't wait and doesn't kill threads: a task that ignores interruption keeps running.
  • awaitTermination(timeout, unit) — changes nothing, only waits for the pool to terminate; false means it didn't terminate in time.
  • close() (Java 19, ExecutorService extends AutoCloseable) — calls shutdown() and waits for all tasks with no timeout. Handy in try-with-resources.

A closed pool can't be reopened — you need a new one. If the pool is never closed, it depends on its threads: fixed, single and scheduled pools keep the JVM alive forever (the threads are not daemons and never die), a cached pool lets the program exit after about 60 s of idleness, and newWorkStealingPool and virtual threads are daemons: the JVM exits right away and unfinished tasks are lost.

7. 

How does ThreadPoolExecutor handle a new task, and what rejection policies are there?

ThreadPoolExecutor is configured with corePoolSize, maximumPoolSize, keepAliveTime, a queue and a RejectedExecutionHandler. A new task is handled like this:

  1. fewer threads than corePoolSize — a new thread is created, even if the others are idle;
  2. core threads are busy — the task goes into the queue;
  3. the queue is full and there are fewer threads than maximumPoolSize — an extra thread is created;
  4. the queue is full and the thread count is at the maximum — the task is rejected.

Extra threads appear only when the queue is full, so with an unbounded LinkedBlockingQueue (as in newFixedThreadPool) maximumPoolSize is never used.

Rejection policies: AbortPolicy (the default) throws RejectedExecutionException; CallerRunsPolicy runs the task in the calling thread and so slows down the task source; DiscardPolicy silently drops the task; DiscardOldestPolicy drops the oldest task in the queue and tries again.

For computational tasks the pool size is set to roughly Runtime.getRuntime().availableProcessors(); for tasks that wait for the network or disk, larger. Different kinds of work are kept in different pools so that hung calls don't stop the calculations.

8. 

What is the difference between scheduleAtFixedRate() and scheduleWithFixedDelay(), and what happens if a periodic task throws an exception?

  • scheduleAtFixedRate(task, initialDelay, period, unit) measures the period from the start of the first run: 0, period, 2·period… If the task takes longer than the period, the next run starts right after the current one ends; two runs of the same task never overlap. Good for a steady rhythm: metrics every second.
  • scheduleWithFixedDelay(task, initialDelay, delay, unit) measures the pause from the end of one run to the start of the next, so the pause is always at least delay. Good for polling an external service or cleaning a cache, where you mustn't overload anything.

With both methods, an exception in the task silently cancels all its following runs. There is no stack trace: the exception is stored in the ScheduledFuture, and the only way to see it is get(), which throws ExecutionException. That's why the body of a periodic task is wrapped in try/catch (Exception e) with logging.

After shutdown(), periodic tasks are cancelled by default, while tasks delayed with schedule() still run when their time comes.

Page 1 of 1