Sub topic 12
Static State and Thread Safety
This chapter assumes you know how to define classes, create objects, use access modifiers, and override methods.
A static field belongs to the class rather than to one object. Java creates one field for the class, and all objects read and write that same field. This makes static state useful for shared information, such as a sequence number. It also creates a concurrency risk when multiple threads access mutable state at the same time.
Why a Plain Static Field Can Fail
A thread is an independent path of execution. Multiple threads can run the same method at nearly the same time.
Consider this operation:
count++;Although it looks like one operation, it has three steps:
- Read
count. - Add one.
- Write the result back.
If two threads read the same old value before either writes, both threads calculate the same new value. One update is lost.
| Shared state | Safe when multiple threads use it? |
|---|---|
| `static final String` | Usually yes, because the reference cannot change and `String` is immutable |
| `static int` changed with `++` | No, because the update is not atomic |
| `AtomicInteger` | Yes for its atomic operations |
| `ConcurrentHashMap` | Yes for its supported concurrent operations |
The problem is not the static keyword by itself. The problem is shared mutable state without a safe way to coordinate access.
Use Atomic Types for Simple Counters
The java.util.concurrent.atomic package provides classes for thread-safe updates. An AtomicInteger offers operations such as incrementAndGet, which reads, increments, and returns the value as one atomic action.
import java.util.concurrent.atomic.AtomicInteger;
public final class IdGenerator {
private static final AtomicInteger NEXT_ID = new AtomicInteger();
private IdGenerator() {
}
public static int next() {
return NEXT_ID.incrementAndGet();
}
public static void main(String[] args) throws InterruptedException {
Thread first = new Thread(() -> System.out.println(next()));
Thread second = new Thread(() -> System.out.println(next()));
first.start();
second.start();
first.join();
second.join();
}
}The field is static because all callers use one sequence. It is final because the AtomicInteger object itself should not be replaced. Its internal value can still change through atomic methods.
Protect Compound Operations
Atomic types protect individual operations. They do not automatically protect a larger sequence of operations.
For example, “check whether a name exists, then add it” must be performed as one protected action. A ConcurrentHashMap provides methods such as putIfAbsent for this purpose.
For more complex state, use synchronization. A synchronized method or block allows only one thread at a time to execute the protected code.
public final class Inventory {
private static int available = 10;
private Inventory() {
}
public static synchronized boolean takeOne() {
if (available == 0) {
return false;
}
available--;
return true;
}
public static synchronized int available() {
return available;
}
}Both methods use the same class lock because they are static synchronized methods. If the field were an instance field, an instance synchronized method would use that particular object’s lock instead.
Testing and Design Costs
Static mutable state survives across method calls and often across tests in the same Java process. One test can change the state that another test expects to be empty. Provide a reset method only when the design requires it, or isolate the state in an object that tests can create afresh.
Shared state also makes dependencies less visible. A method that reads a static configuration or counter can behave differently depending on what other code did earlier. Prefer immutable static values for constants. Use an instance object when callers need separate state, substitution in tests, or different configurations.
Exercise
Why can static int count; count++; lose updates when two threads run it together, and what is one suitable fix?
Show answer
The increment consists of separate read, add, and write steps, so threads can overwrite each other's results. Use AtomicInteger.incrementAndGet() or protect the update with synchronization.