Sub topic 2
What Makes State Shared and Mutable
In the last chapter you started threads and watched them run at the same time. This chapter answers a question that comes before any locking: which data in your program can threads actually trouble each other over? The answer depends on two properties, shared and mutable. Once you can spot data that has both, you know where thread-safety problems can happen and where they cannot.
Two Words That Matter
State is the data a program holds at a given moment: the values in its variables and object fields.
Shared state is data that more than one thread can reach. If thread A and thread B can both get to the same variable or object, that variable or object is shared.
Mutable state is data that can change after it is created. A field that a setter can overwrite is mutable. A final field holding a number is not.
Trouble needs both properties at once:
| Shared? | Mutable? | Risk |
|---|---|---|
| No | No | Safe. Only one thread sees it, and it never changes. |
| No | Yes | Safe. It changes, but only one thread ever touches it. |
| Yes | No | Safe. Many threads read it, but nobody can change it. |
| Yes | Yes | Needs protection. Threads can step on each other. |
Only the last row is dangerous. The rest of this tutorial is about the tools for handling that row, or for moving your data out of it.
Where Data Lives: Stack and Heap
To know whether data is shared, it helps to know where Java keeps it.
- The stack is a private memory area that each thread gets for itself. Local variables and method parameters live there. Every thread has its own stack, so one thread cannot see another thread's local variables.
- The heap is one big memory area that all threads in the program use. Every object you create with
newlives on the heap, along with its fields.
A local variable that holds a number like int stays on the thread's own stack. A local variable that holds an object only holds a reference, which is the address of the object on the heap. If two threads hold references to the same object, they share it, even though each reference is a separate local variable.
Kinds of Variables and Their Default Risk
| Kind of variable | Where it lives | Shared by default? |
|---|---|---|
| Local variable (primitive, like `int`) | Thread's stack | No |
| Method parameter (primitive) | Thread's stack | No |
| Local variable holding an object reference | Reference on stack, object on heap | Only if the reference is handed to another thread |
| Instance field | Inside an object on the heap | Yes, if the object is reachable by several threads |
| Static field | On the heap, one copy per class | Yes, any thread can reach it |
Static fields are the easiest to miss. A static field has exactly one copy for the whole program, so every thread that runs code in your program can reach it.
A Worked Example: Local Versus Shared
The program below runs the same task on two threads. Each thread counts with a local variable, and each thread also adds to a field of a shared object.
public class LocalVsShared {
static class Tally {
int total = 0; // instance field: lives on the heap
}
public static void main(String[] args) throws InterruptedException {
Tally shared = new Tally(); // one object, both threads will use it
Runnable task = () -> {
int local = 0; // local variable: each thread has its own copy
for (int i = 0; i < 100_000; i++) {
local++;
shared.total++;
}
System.out.println(Thread.currentThread().getName()
+ " local = " + local);
};
Thread t1 = new Thread(task, "worker-1");
Thread t2 = new Thread(task, "worker-2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("shared.total = " + shared.total);
}
}Run it a few times. You will see something like this:
worker-1 local = 100000
worker-2 local = 100000
shared.total = 137412Each local is always exactly 100000, because each thread has its own copy on its own stack. shared.total is often less than 200000, and the value changes between runs. Both threads hold a reference to the same Tally object, and its total field is mutable. That field is shared and mutable, so it sits in the dangerous row of the table. The next chapter explains exactly how the counts get lost.
Edge Case: The "Effectively Final" Rule Does Not Protect You
Java does not let a lambda change a captured local variable. The variable must be effectively final, meaning it is never reassigned after it gets its value. This code does not compile:
public class CaptureError {
public static void main(String[] args) {
int count = 0;
Runnable task = () -> {
count++; // compile error: count must be effectively final
};
new Thread(task).start();
}
}The compiler reports an error such as "local variables referenced from a lambda expression must be final or effectively final." This stops you from sharing a captured primitive.
It does not stop you from sharing an object. The reference must stay the same, but the object it points to can still change:
public class CaptureLoophole {
public static void main(String[] args) throws InterruptedException {
int[] count = {0}; // the reference never changes, the contents do
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count[0]++;
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count[0]);
}
}This compiles, and it has the same problem as Tally. The array is one object on the heap that both threads can reach, and its contents can change.
Ways Data Becomes Shared
Data rarely becomes shared on purpose. These are the common ways it happens:
- Static fields. Any thread can reach them.
- Passing an object to a thread, for example capturing it in a
Runnableor a lambda. - Storing an object in a shared place, such as a static list, a cache, or a field of an object that is already shared.
- Returning an internal field from a method. A getter that returns your private
Listlets callers on other threads change it. - Frameworks that use threads for you. A web server can call the same object from many request threads at once.
Three Ways Out of the Dangerous Row
Every thread-safety tool in Java comes down to one of three ideas:
- Don't share. Keep the data on one thread. Later chapters cover this as thread confinement.
- Don't mutate. Make the data unchangeable after it is created. This is immutability.
- Coordinate access. If data must be both shared and mutable, make threads take turns using it, with tools such as
synchronized, locks, and atomic classes.
The first two options are often the simplest, because data outside the dangerous row needs no extra code at all.
Exercise
In the LocalVsShared program, suppose you move the line "Tally shared = new Tally();" inside the lambda, before the loop. Will the final printed value of shared.total still be wrong? Explain using the words shared and mutable.
Show answer
The program no longer compiles as written, because main can no longer see the variable shared to print it. The threading point is still the same: each thread would create its own Tally object, so no other thread could reach it. The field stays mutable but is no longer shared, so each thread's own total would always be exactly 100000. Data that is not shared is safe even when it changes.
Exercise
A class has the field "private static final List<String> NAMES = new ArrayList<>();" and several threads call NAMES.add(...). Is this safe because the field is final? Why or why not?
Show answer
It is not safe. Because the field is static, every thread can reach it, so it is shared. The final keyword only stops the variable from pointing to a different list. The ArrayList itself is still mutable, so threads adding at the same time can corrupt it or lose items.
Exercise
For each item, say whether it is shared, mutable, both, or neither when used inside a Runnable run by two threads: (a) an int declared inside run(), (b) a static int counter, (c) a final String field of an object both threads use.
Show answer
(a) Neither shared nor a risk: each thread has its own copy on its stack, so it is mutable but not shared. (b) Both shared and mutable, so it needs protection. (c) Shared but not mutable: the field is final and String objects cannot change, so it is safe to read from both threads.