Sub topic 12
Static state and thread safety
This chapter assumes you know how to declare static fields and methods, how static final constants work, and how to start a Thread with a Runnable. It covers why mutable static fields cause concurrency bugs, how to fix them, and which static patterns are already safe.
Why static state is exposed to threads
An instance field belongs to one object. If only one thread ever holds a reference to that object, no other thread can touch the field. A static field belongs to the class, and any thread in the JVM can reach it by name. Every thread that runs code in the class shares the same copy.
This means a static field is shared by default, whether or not you intended that. A web server that handles requests on many threads, a thread pool, and a parallel stream all run your static methods concurrently. If those methods read and write a static field, you have shared mutable state, and you must protect it.
Two kinds of static state are safe without extra work:
- Static final fields that hold immutable values, such as
int,String, or aMapthat is never modified after the class finishes initializing. - Static methods that use only their parameters and local variables. Each call gets its own stack frame, so threads do not interfere.
The trouble starts with static fields that change after initialization.
A lost update with a plain static int
The ++ operator looks like one step, but it is three: read the value, add one, write the result back. Two threads can interleave those steps.
public class RaceDemo {
private static int counter = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
counter++;
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter);
}
}Two threads each add 100,000, so you might expect 200000. On most machines the output is lower, and it changes from run to run. Some increments were lost.
This bug is a race condition. It does not always show up in small tests, which makes it hard to catch. A program can pass on your laptop and fail under production load.
Fix 1: atomic types
For a single counter or flag, use a class from java.util.concurrent.atomic. Its operations run as one indivisible step.
import java.util.concurrent.atomic.AtomicInteger;
public final class IdGenerator {
private static final AtomicInteger NEXT = new AtomicInteger();
private IdGenerator() {
}
public static int next() {
return NEXT.incrementAndGet();
}
}The field is static final, so the reference never changes. The state lives inside the AtomicInteger, which handles concurrent updates itself. Prefer this fix when the shared state is one number, one boolean, or one reference.
Atomics protect each single call, not a sequence of calls. This check-then-act code is still racy:
if (REMAINING.get() > 0) {
REMAINING.decrementAndGet(); // another thread may have taken the last one
}Use a compare-and-set loop so the check and the update succeed or fail together:
import java.util.concurrent.atomic.AtomicInteger;
public final class Tickets {
private static final AtomicInteger REMAINING = new AtomicInteger(5);
private Tickets() {
}
public static boolean tryTake() {
while (true) {
int current = REMAINING.get();
if (current == 0) {
return false;
}
if (REMAINING.compareAndSet(current, current - 1)) {
return true;
}
}
}
}compareAndSet writes the new value only if the field still holds the value you read. If another thread changed it, the call returns false and the loop tries again.
Fix 2: synchronized static methods
When several fields must change together, or the logic is more than one atomic operation, use a lock. A synchronized static method locks on the Class object, such as SyncCounter.class.
public final class SyncCounter {
private static int count = 0;
private SyncCounter() {
}
public static synchronized void increment() {
count++;
}
public static synchronized int get() {
return count;
}
}Both methods use the same lock, so only one thread runs either of them at a time. Reads need the lock too. Without it, a reader might not see the latest write.
Locking on the wrong object
A common mistake is protecting static state with an instance lock:
public class Broken {
private static int total;
public synchronized void add() { // locks "this", not the class
total++;
}
}Each Broken object has its own lock. Two threads calling add() on different objects hold different locks, so both update total at once. A lock protects shared data only when every thread uses the same lock. Static data needs a class-level lock: a static synchronized method, or synchronized (Broken.class), or a private static final Object LOCK.
Fix 3: thread-safe collections
A static HashMap or ArrayList that several threads modify is unsafe. Concurrent writes can lose entries or corrupt the structure. Use a concurrent collection and its atomic methods.
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class PageStats {
private static final ConcurrentMap<String, Integer> HITS = new ConcurrentHashMap<>();
private PageStats() {
}
public static void record(String page) {
HITS.merge(page, 1, Integer::sum);
}
public static int hits(String page) {
return HITS.getOrDefault(page, 0);
}
}merge performs the read, add, and write as one atomic step per key. The unsafe version of the same code, HITS.put(page, HITS.get(page) + 1), has the same lost-update problem as counter++, even on a ConcurrentHashMap.
Visibility and `volatile`
Atomicity is one problem. Visibility is another. Without synchronization, one thread's write to a static field may not become visible to another thread for an unbounded time, because of caching and compiler reordering.
public class Worker {
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (running) {
Thread.onSpinWait();
}
System.out.println("stopped");
});
t.start();
Thread.sleep(100);
running = false;
t.join();
}
}Marking running as volatile guarantees that the worker sees the change. Without volatile, the loop might never end. Note that volatile gives visibility only. It does not make count++ atomic, so it does not fix RaceDemo. Use it for flags that one thread writes and others read.
Static initialization is already thread-safe
The JVM runs a class's static initializers exactly once, and it guarantees that other threads see the result. This makes some static patterns safe without extra code:
- A
static finalfield assigned in a declaration or static block is safely visible to all threads after initialization. This is why theConfigclass from the earlier chapter, with itsCollections.unmodifiableMap, is safe to read from many threads. - The wrapper is safe only because nobody modifies the underlying map after the static block ends. If you keep a reference to the original
HashMapand change it later, readers are unprotected.
The same guarantee gives you lazy, thread-safe singletons through the holder idiom:
public final class Registry {
private Registry() {
}
private static class Holder {
static final Registry INSTANCE = new Registry();
}
public static Registry getInstance() {
return Holder.INSTANCE;
}
}Holder is not loaded until getInstance() first uses it. The JVM then initializes it once, and no explicit locking is needed. Note that the Registry object itself must still be thread-safe if it has mutable fields.
Choosing a fix
| Situation | Fix |
|---|---|
| One counter, flag, or reference | `AtomicInteger`, `AtomicLong`, `AtomicBoolean`, `AtomicReference` |
| Several fields that change together | `static synchronized` methods or a private static lock object |
| Shared map or list | `ConcurrentHashMap`, `CopyOnWriteArrayList`, atomic methods like `merge` |
| Stop flag written by one thread | `volatile boolean` |
| Data never changes after startup | `static final` with an immutable or unmodifiable value |
| State that does not need to be shared | Remove the static field; pass state as parameters or keep it in an instance |
The last row is usually the best choice. Synchronization adds cost and complexity. It also makes tests harder, because static state persists between tests in the same JVM and tests can affect each other. The cheapest way to make shared state safe is to not share it.
Common errors
- Using
volatileon a counter and expecting++to be atomic. - Synchronizing an instance method to protect a static field.
- Reading a synchronized field without the lock.
- Combining two atomic calls (
getthenset) and assuming the pair is atomic. - Using
SimpleDateFormator another non-thread-safe object in astatic finalfield. The reference is final, but the object's internal state is mutable and shared. Usejava.time.format.DateTimeFormatter, which is immutable. - Believing that
static finalmakes an object immutable. It makes the reference constant, not the object it points to.
Exercise
A class has private static int total; and the method public synchronized void add(int n) { total += n; }. Two threads call add on two different objects of this class. Is total updated safely? Explain, and give two ways to fix it.
Show answer
No. A synchronized instance method locks on this, and the two objects have different locks, so both threads can run total += n at the same time and lose updates. Fix 1: make the method static synchronized, so all callers use the class lock. Fix 2: change total to private static final AtomicInteger and call total.addAndGet(n).
Exercise
Why does RaceDemo usually print less than 200000, and why does declaring counter as volatile not fix it?
Show answer
counter++ is three steps (read, add, write). Two threads can read the same value and both write back the same result, so one increment is lost. volatile makes writes visible to other threads but does not make the three steps one indivisible operation. Use AtomicInteger.incrementAndGet() or a lock instead.