Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Java › Threads and concurrency

Thread count and context switching

Adding threads does not keep making things faster

Why it exists — If a new thread is created every time a task arrives, the number of threads grows without limit when requests pile up. Threads added after the CPU is already fully busy add no throughput and only take up memory, and creating and destroying threads costs something for every task. A thread pool creates a fixed number of threads in advance and reuses them, so the number of threads running at the same time can be capped to suit the kind of work.

Where it's used today — Tomcat handles requests with threads from a thread pool (server.tomcat.threads.max), and in Java code, tasks such as image conversion or external API calls are handed to a pool with ExecutorService. For computation-heavy tasks the pool size is set near the number of cores, and for tasks that wait for a database or an external response it is set much larger. For tasks that mostly wait, virtual threads are sometimes used instead.

A CPU core runs only one thread at any given moment. When more threads want to run than there are cores, the operating system runs them in turn, each for a short time (context switching). Throughput then stops growing, and only the time for one task to finish gets longer. The right number of threads is completely different depending on whether the tasks mostly compute or mostly wait. The numbers on screen are values actually measured on Linux with JDK 21.

Checked against real execution · Values actually measured for all 54 combinations with JDK 21 on Linux

Concepts in this lab

Processes and threads
A process is a running program, and the operating system gives it its own independent memory space. A thread is a flow of execution that does the actual work inside a process. The threads of one process share memory (heap, code, and data), and each has only its own stack. This makes it easy for threads to exchange data, but it also causes problems when they touch the same data at the same time.
Context switching
This is the process in which the CPU stops the thread (or process) it is running and switches to run another one. The state of the current work must be saved and the state of the next work must be loaded, and the switch itself takes time. When there are far more threads than CPU cores, the time spent on switching grows relative to the time spent on actual work.
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.
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

Running with the default settings

  1. Cores: 4. Threads: 16. One task is a computation that takes about 10ms when it has a core to itself, and each thread computes without a break.
  2. At any given moment, the average number of threads that want the CPU is 16 (16 × 100%). The number of cores is 4, so there are not enough cores. The operating system puts the threads on the cores in turn, each for a short time. The measured CPU usage is 100%.
  3. Context switches counted by the Linux kernel per second: 1072. Of these, 1016 are a thread that was using the CPU being preempted by another thread (nonvoluntary), and 56 are a thread giving up the CPU by itself in order to wait (voluntary). About 4 threads share each core, so each thread is stopped whenever it is not its turn.
  4. Result: tasks handled per second: 342, average time for one task to finish: 46.8ms (about 10ms when it does not compete with other threads for a core). Measured with the number of threads set to 4, the values were 348 per second and 11.5ms per task.

Result of this run

Code

int cores = Runtime.getRuntime().availableProcessors();   // 4

// mostly computation: as many threads as cores is enough
ExecutorService pool = Executors.newFixedThreadPool(16);

for (Photo photo : photos) {
    pool.submit(() -> resize(photo));              // one task = about 10ms of computation
}
// Photo, photos, and resize() are names made up for this example (only the needed part is shown)

Assumptions of this model

The numbers on screen are not calculated by a model. All of them are measured values. A program that queues tasks in a fixed-size thread pool, as in the code on screen, was run in 54 combinations in a Linux container (Docker Desktop, kernel 6.18.33.2-microsoft-standard-WSL2, JDK 21.0.13.1 from the official image eclipse-temurin:21-jre). The number of cores was set by pinning the process to 1, 2, or 4 different physical cores with the --cpuset-cpus option of Docker (the CPU is AMD Ryzen 5 5600 6-Core Processor). A task that mostly computes is a fixed amount of computation (about 10ms on one core when nothing interferes), and for a task that mostly waits, Thread.sleep(90) after the same computation stands in for waiting for an external response. Other programs were running on the same computer during the measurement. So for each combination, 6 seconds were measured and the values of the 3 consecutive seconds with the most finished tasks were taken, this was repeated 4 times, and the values of the repetition with the highest throughput are shown on screen. Some variation still remains (for example, the throughput per second of 4 threads that mostly compute on 4 cores was 312.7, 302.3, 348.0, 346.7 across the repetitions), so small differences between nearby values carry no meaning, and the numbers vary with the computer and from run to run. CPU usage is the CPU time used by the process divided by the measurement time and the number of cores, so it also includes time used by JVM threads other than the worker threads (in some combinations with only one or two threads it is higher than the calculation), and the number of context switches is the sum of voluntary_ctxt_switches and nonvoluntary_ctxt_switches, which the Linux kernel counts for each thread and reports in /proc. The numbers of threads in each state in the diagram are averages calculated from the measured CPU usage and throughput. "Number of cores × (1 + wait time ÷ compute time)" is a widely cited guideline in the field of Java concurrency. The default maximum of 200 threads for the embedded Tomcat in Spring Boot was not verified in this run. It is the value in the Spring Boot documentation.

Previous lab: Thread pool · Next lab: Sequential and parallel calls

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these