Sub topic 1
Threads in Java: Running Code Concurrently
Threads
A thread is a path of execution inside a program. Every Java program starts with one thread, called the main thread. You can start more threads so that several tasks run at the same time. Running tasks at the same time is called concurrency.
Shared Mutable State
State is the data your program keeps, such as fields. Data is shared when more than one thread can reach it. It is mutable when it can change after it is created. A static field that two threads both update is shared mutable state. This is where thread problems start.
Race Conditions
A race condition is a bug where the result depends on the timing of the threads. Run this program a few times:
public class RaceDemo {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count++;
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}You might expect 200000. You will often see a smaller number, and it changes from run to run.
Atomicity
An action is atomic when it happens as one step that no other thread can interrupt. count++ looks like one step, but the computer does three steps: read the value, add 1, and write the new value back. If two threads both read 5 before either one writes, both write 6, and one increment is lost.
Visibility
Visibility is about whether one thread can see a value that another thread wrote. To run faster, each processor may keep its own copy of a variable. So a thread can keep reading an old value even after another thread changed it. This is a separate problem from atomicity. A step can be atomic and still be invisible to other threads.
Exercise
Two threads each run count++ 1,000 times on a shared int that starts at 0. Why might the final value be less than 2,000?
Show answer
count++ is three steps: read, add, and write. If both threads read the same value before either one writes, one thread's update overwrites the other's and that increment is lost.
Exercise
Thread A sets a field to true. Thread B keeps reading the field and still sees false. Is this an atomicity problem or a visibility problem?
Show answer
It is a visibility problem. The write itself is a single step, but Thread B is not seeing the new value.