Skip to main content
Executors and thread pools · Topic 3 of 7

ThreadPoolExecutor settings

Definition​

ThreadPoolExecutor lets you set the core size, the maximum size, the queue and what to do when it is full. Tasks first fill the core threads, then wait in the queue, and only when the queue is full are extra threads started. If everything is full, the rejection policy decides.

Example code​

A small pool that rejects work when it is full

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Demo {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
1, 2, // core 1 thread, up to 2 threads
60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1), // the queue holds 1 waiting task
new ThreadPoolExecutor.AbortPolicy()); // throw when everything is full

Runnable slow = () -> { try { Thread.sleep(300); } catch (InterruptedException ignored) { } };

pool.execute(slow); // runs on the core thread
pool.execute(slow); // waits in the queue
pool.execute(slow); // queue is full: starts the second thread
try {
pool.execute(slow); // no thread and no queue space left
} catch (RejectedExecutionException e) {
System.out.println("rejected: the pool is full");
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}

// Output:
// rejected: the pool is full

Finished this page? Track your progress (saved only in your browser).