Dev Learning Lab

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

Learn › Java › Threads and concurrency

Processes and threads

Two ways to add more workers

Why it exists — With only one flow of execution, other tasks must wait until one task finishes. The operating system runs each program as a process with its own separate memory, so that a failure in one program does not spread to another, and puts several threads, the flows of execution, in one process, so that they share memory while carrying out several jobs at the same time.

Where it's used today — Tomcat handles several users at the same time in one process by assigning a thread from a thread pool to each request, and the Chrome browser divides processes by site so that if the tab of one site dies, the tabs of other sites keep running. Starting the same application on several servers or in several containers is also a way of dividing it into processes. Work that exchanges data often is divided into threads, and work whose failures must not spread to each other is divided into processes.

When you run a program, one process is created, and the threads inside it are what actually execute the code. This lab runs three tasks that take 0.3 seconds each in three ways: on one thread, on three threads in one process, and in three processes. The ways differ in whether memory is shared and in what happens to the rest when one of them dies.

Checked against real execution · Checked by running the 9 combinations on JDK 21

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.
Inter-process communication (IPC)
Why it exists — If each process has its own memory, they cannot damage each other, but in exchange they cannot read each other's variables directly. IPC lets them exchange values only through channels that the operating system provides, so they can cooperate while staying separated.
Where it's used today — Joining commands with | in a shell is a pipe, and when connecting to the Docker daemon or PostgreSQL on the same computer, a Unix domain socket is sometimes used.
This is how processes that each have their own independent memory exchange data. The methods include pipes, message queues, shared memory, and sockets. Communication between server programs mostly uses HTTP or a message broker, which run on top of sockets.
Run-time data areas
These are the memory areas that the JVM uses while it runs a program. The areas that each thread has for itself are the pc register, the Java Virtual Machine stack, and the native method stack, and the areas shared by all threads are the heap and the method area. They are the basis for understanding which data is shared between threads.
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.

Try these

Running with the default settings

  1. The program is run, which creates 1 process. The operating system gives this process memory, and there is one counter variable in it. Inside the process, 3 threads are created. Each thread has only its own flow of execution (its stack), and the threads share the memory of the process.
  2. The 3 threads each take one task and start at the same time. They do not wait for one another.
  3. The remaining threads finish their tasks and increment the same counter. counter is 3. Several threads share one variable, so the line that increments it uses synchronized, which lets only one thread at a time increment it. Without it, two threads can read the same value and overwrite each other, and the result can be smaller than the number of increments (the next concept, race conditions).

Result of this run

Code

public class Main {                         // Main and work are names made up for this example
    static int counter = 0;                 // a variable in the memory of the process

    static void work(int id) {
        try { Thread.sleep(300); } catch (InterruptedException e) { return; }   // a task that takes 0.3 seconds
        synchronized (Main.class) { counter++; }   // only one thread at a time increments it
    }

    public static void main(String[] args) throws Exception {
        // 3 threads in the same process
        for (int i = 1; i <= 3; i++) {
            int id = i;
            new Thread(() -> work(id)).start();
        }
    }
}

Assumptions of this model

The 9 combinations were checked by actually running them on JDK 21 in our test environment. With 3 threads it took 0.3 seconds and with 1 thread 0.9 seconds. Running the code with synchronized on counter++ 30 times with 3 threads gave 3 in the shared counter every time, whereas the 3 processes each had 1. Running it 30 times without synchronized gave 3 in only 7 runs, 1 in 21 runs, and 2 in 2 runs, because the three threads wake up at almost the same moment, read the same value, and overwrite each other (a race condition). An exception ended only the thread it was thrown in, System.exit ended every thread in the same process, and with separate processes, every process other than the one that died terminated normally. The time and memory it takes to create a process are not shown on the screen (in reality they are much larger, because a new JVM is started each time). The 3-process code works when the java command can be found on the PATH and it is run in the folder that contains Main.class (from another folder, you must pass the class path with -cp). The first process ends without waiting for the working processes, but they keep running regardless, and the results were the same. The counter value of each process was checked in a separate verification program that waited for each process to finish with waitFor() and read its output.

Previous lab: Parallel streams and the common pool · Next lab: Creating threads and thread states

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these