The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › Threads and concurrency
Thread pool
What changes when you add more threads
Why it exists — If a new thread is created every time a task arrives, the number of threads grows with the number of requests when many requests come at once. Each thread uses memory, and switching between threads has a cost, so the whole server can slow down or stop. A thread pool reuses threads it has already created and puts an upper limit on their number. Extra tasks wait in a queue or are rejected, so the server handles only as many tasks at the same time as it can bear.
Where it's used today — A servlet container such as Tomcat handles incoming requests with a thread pool. In application code, you create a pool with ExecutorService to call several external APIs at the same time and collect the results, or to run long tasks separately. When there are very many tasks that spend most of their time waiting, some applications use no pool and create a virtual thread for each task instead.
A thread pool reuses the threads it has created, up to a set number, instead of creating and discarding a thread for every request. When a request comes in, one thread handles it from start to finish. When all the core threads are busy, requests wait in a queue; when the queue is full, more threads are created up to the maximum; and requests beyond that are rejected. This lab shows how waiting and rejection change with the number of threads and the size of the queue.
Checked against real execution · Checked against the results of actually running a ThreadPoolExecutor
Concepts in this lab
- Thread pool
- This structure keeps a fixed number of threads and reuses them, so that threads are not created and destroyed every time they are needed. It reduces the cost of creating threads, and by limiting the number of threads that run at the same time, it prevents excessive memory use and context switching. Tasks to be processed pile up in a queue, and an idle thread takes one and runs it. Tomcat's request handling and a DB connection pool follow the same idea.
- How ThreadPoolExecutor handles a new task
- Java's thread pool implementation handles an incoming task in the following order. If fewer threads than corePoolSize are running, it creates a new thread. Otherwise, it puts the task in the queue. If the queue is full, it creates more threads, up to maximumPoolSize. Beyond that, it rejects the task. Contrary to intuition, with a bounded queue the number of threads grows only after the queue is full (with an unbounded queue it does not grow).
- Tomcat's threading model
- Why it exists — If one thread handles a request all the way through, even code that waits for a database response can be written from top to bottom in order, without being split into callbacks. Tomcat takes those threads from a pool created in advance and sets an upper limit on their number, so threads do not grow endlessly even when requests pile up.
- Where it's used today — A Spring MVC service with slow external calls or many concurrent requests tunes server.tomcat.threads.max together with the size of the database connection pool. When requests seem to be stuck, you look in a thread dump to see at which line a request processing thread such as http-nio-8080-exec-1 is waiting.
- Tomcat manages its request processing threads in a pool, and one thread takes one request and handles it until the response is finished. The number of requests it can handle at the same time is limited by the maximum number of threads (200 by default). Unlike the standard Java ThreadPoolExecutor, when no thread is idle it adds threads up to the maximum first, and new requests wait only when all of them are in use. A thread stays occupied even while the request is waiting on a database or an external call.
- Blocking and non-blocking
- Blocking means that the calling thread is stopped until the called task finishes and cannot do other work. Non-blocking means that the call returns right away even though the task has not finished, so the thread can do other work. A typical JDBC call is a blocking call: the thread is stopped until the DB response arrives.
Try these
- Default settings — Core pool size 2, maximum pool size 4, queue capacity 2, and 10 requests. Some requests are rejected.
- More threads only — Core pool size 4 and maximum pool size 8. See how the rejections and the waiting change.
- A longer queue only — The threads stay the same and only the queue capacity grows to 10. Fewer requests are rejected, but requests wait longer.
- An unbounded queue — Confirm that the maximum pool size is never used.
- Requests that finish quickly — Each request takes 0.5s. The same number of threads can now keep up.
Running with the default settings
- Request 1 arrives. The pool has fewer threads than the core pool size (2), so it creates thread 1, which handles the request right away.
- Request 2 arrives. The pool has fewer threads than the core pool size (2), so it creates thread 2, which handles the request right away.
- Request 3 arrives. Every thread is busy (2 in the pool). Instead of adding a thread, the pool puts the request in the queue (waiting: 1/2).
- Request 4 arrives. Every thread is busy (2 in the pool). Instead of adding a thread, the pool puts the request in the queue (waiting: 2/2).
- Request 5 arrives. The queue is full. Only now does the pool create an additional thread, thread 3, to handle it (up to a maximum of 4).
- Request 6 arrives. The queue is full. Only now does the pool create an additional thread, thread 4, to handle it (up to a maximum of 4).
- Request 7 arrives. Every thread is busy (the maximum, 4) and the queue is also full. The request is rejected.
- Request 8 arrives. Every thread is busy (the maximum, 4) and the queue is also full. The request is rejected.
- Request 9 arrives. Every thread is busy (the maximum, 4) and the queue is also full. The request is rejected.
- Request 10 arrives. Every thread is busy (the maximum, 4) and the queue is also full. The request is rejected.
- Thread 1 finishes request 1, takes request 3 from the head of the queue, and starts handling it. Request 3 waited 1.6s.
- Thread 2 finishes request 2, takes request 4 from the head of the queue, and starts handling it. Request 4 waited 1.6s.
- Thread 3 finishes request 5. No request is waiting, so the thread becomes idle.
- Thread 4 finishes request 6. No request is waiting, so the thread becomes idle.
- Thread 1 finishes request 3. No request is waiting, so the thread becomes idle.
- Thread 2 finishes request 4. No request is waiting, so the thread becomes idle.
Result of this run
- The requests that were handled spent 0.5s in the queue on average, and the one that waited longest spent 1.6s there.
- To get rid of the rejections, add threads, make the queue longer (requests then wait longer), or reduce the time it takes to handle a request.
Code
// Only the lines inside main are shown (class, main declaration, imports, and the declaration of the example method handle() omitted)
ExecutorService pool = new ThreadPoolExecutor(
2, // core pool size
4, // maximum pool size
60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(2)); // queue capacity 2
for (int i = 1; i <= 10; i++) {
try {
pool.execute(() -> handle()); // each request takes 2.0s
} catch (RejectedExecutionException e) {
// when all threads and the queue are full, the default policy (AbortPolicy) throws this exception
}
Thread.sleep(200); // a request arrives every 0.2s
}
Assumptions of this model
While a request is being handled, one thread is tied up for the whole handling time (a request that waits for a slow database or external API). The model assumes that adding threads costs nothing. In reality each thread uses memory, and when more threads want the CPU than there are cores, the cost of switching between them grows. The order in which threads are assigned (core threads → queue → threads up to the maximum → rejection) is the same as the actual rule of the Java ThreadPoolExecutor, and it was checked against real execution. The thread pool that Tomcat uses for handling requests follows a different order: when no thread is idle, it adds threads up to the maximum before putting requests in the queue.
Previous lab: Deadlock · Next lab: Thread count and context switching