Thread Safety in Java: Thread-Safe Classes and Collections
Thread safety in Java is the property of a class to behave correctly when several threads access the same object at the same time, without any extra synchronization by the calling code. A thread-safe class keeps its invariants under any interleaving of threads: no updates are lost, and readers never see the object in a half-updated state. You get there through synchronization, immutability, atomic classes, or by not sharing state at all.
A thread-safe class doesn't automatically make your code thread-safe, though. Two threads each increment a counter in a ConcurrentHashMap 100,000 times using a get() followed by a put(), and instead of 200,000 the program prints something like 104967, without a single exception. Every method of the map is atomic; the read-then-write pair is not. The breakdown and the fix are in Thread-Safe Class ≠ Thread-Safe Code.
What Thread Safety Means
A class is thread-safe if its methods can be called from several threads at once and the result is the same as for some sequential execution of those calls. The calling code doesn't have to wrap them in synchronized: the class takes care of everything it needs on its own.
The problem comes from shared mutable state. If two threads read and change the same field without synchronization, you get a race condition: updates are lost, and another thread may see a stale value. What this looks like on count++, and why that operation isn't atomic, is covered in detail in Thread Synchronization in Java.
That leads to a simple observation: if there's no shared mutable state, there's nothing to protect. A class without fields, a class whose fields are all final and of immutable types, a method's local variables are thread-safe without a single lock. Synchronization is needed only where several threads share data that changes.
The term applies to a class as a whole, not to a single method. The JDK documentation says outright that classes like ConcurrentHashMap, AtomicInteger and StringBuffer are thread-safe, while for ArrayList, HashMap and StringBuilder it says they are not synchronized, and if several threads share one instance, the calling code has to provide the synchronization.
How to Make a Class Thread-Safe
There are six main ways to make a class thread-safe in Java: keep no shared state, make the state immutable, confine it to one thread, guard it with synchronization, replace fields with atomic classes, or keep the data in a thread-safe collection. The first three remove the cause of the race; the rest protect shared mutable data.
| Approach | How it works | Example | What it costs |
|---|---|---|---|
| No shared state (stateless) | The class works only with parameters and local variables, and each thread has its own copies on its own stack | A price calculator, a validator, most services without fields | Nothing, but it doesn't always fit: data has to live somewhere |
| Immutability | The state is set in the constructor and never changes, so a race has nothing to grab onto | String, Integer, LocalDate, List.of(…) | Every "change" creates a new object |
| Thread confinement | The object is reachable by one thread only; ThreadLocal gives each thread its own copy | ThreadLocal<SimpleDateFormat>, an object created and used inside a single run() | Data isn't shared; with ThreadLocal in thread pools, values must be cleaned up with remove() |
| Synchronization | Methods or blocks that touch shared fields are synchronized on one monitor (details) | StringBuffer, Vector, Hashtable | Threads wait for each other; with several monitors there's a risk of deadlock |
| Atomic classes | Operations on a single variable run atomically via CAS, without locking | AtomicInteger, AtomicLong, AtomicReference | Only one variable is atomic; an invariant spanning two fields can't be protected this way |
| Thread-safe collections | The collection itself coordinates thread access to its data | ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue | Compound operations made of several calls are still not atomic |
In practice these approaches are combined. A typical service has no mutable fields (stateless), accepts and returns immutable objects, and keeps its only shared state, a cache, in a ConcurrentHashMap. Such a class is thread-safe even though the word synchronized never appears in it.
The order of the table isn't random: the higher the approach, the less room it leaves for mistakes. You can't "forget to synchronize" an immutable object, whereas in a synchronized class every new method that touches the fields is one more chance to miss a synchronized.
Immutable Classes
An immutable class is a class whose objects can't change state after they are created. Such objects are thread-safe automatically: you can pass them between threads freely without synchronization, because no thread is able to corrupt them. String, the wrappers Integer, Long and friends, BigDecimal, and the date-time classes LocalDate, LocalDateTime and Instant are all immutable.
To make a class immutable, follow five rules:
- Declare the class
final, otherwise a subclass can add mutable fields or override methods. - Make all fields
private final. - Provide no setters or other methods that change fields.
- Copy mutable objects received in the constructor (lists, arrays,
Date): a defensive copy. - Don't let getters hand out mutable internal objects: return a copy or an unmodifiable view.
import java.util.List;
public final class Order {
private final String id;
private final List<String> items;
public Order(String id, List<String> items) {
this.id = id;
this.items = List.copyOf(items); // defensive copy, and an unmodifiable one
}
public String getId() {
return id;
}
public List<String> getItems() {
return items; // safe to return: a List.copyOf list can't be modified
}
} List<String> source = new ArrayList<>(List.of("book"));
Order order = new Order("A-1", source);
source.add("pen"); // modify the original list
System.out.println(order.getItems()); // the order hasn't changed
order.getItems().add("notebook"); // try to modify it through the getter [book]
Exception in thread "main" java.lang.UnsupportedOperationException Without List.copyOf, the order would hold a reference to someone else's ArrayList, and a call to source.add("pen") from any thread would change the "immutable" object. List.copyOf (Java 10) throws NullPointerException if the list contains null; if null elements are allowed, use Collections.unmodifiableList(new ArrayList<>(items)).
final fields come with one more guarantee that ordinary fields don't have (JLS 17.5): once the constructor finishes, any thread that obtains a reference to the object sees the correct values of its final fields, even if the reference was passed without synchronization. The condition is that the constructor must not let this escape, for example by registering the object in a shared list before initialization is complete.
A record is only immutable on the surface
A record (Java 16) has private final fields, no setters, and is implicitly final, so three of the five rules are satisfied for free. But record Order(String id, List<String> items) stores the list it receives as is: you have to make the defensive copy yourself in a compact constructor, items = List.copyOf(items);.
Atomic Classes: AtomicInteger and CAS
The atomic classes in java.util.concurrent.atomic (Java 5), namely AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference, perform operations on a single variable atomically and without locks. Under the hood they use the CPU's CAS (compare-and-set) instruction: "write the new value only if the current one still equals the expected one".
| AtomicInteger method | What it does | What it returns |
|---|---|---|
get() / set(v) | Read and write with a visibility guarantee, like volatile | The current value / nothing |
incrementAndGet() | Atomic equivalent of ++count | The new value |
getAndIncrement() | Atomic equivalent of count++ | The old value |
addAndGet(delta) | Adds delta | The new value |
compareAndSet(expect, update) | Writes update only if the current value equals expect | true if the write succeeded; false if someone has already changed the value |
updateAndGet(fn), accumulateAndGet(x, fn) | Applies a function atomically (Java 8); on contention the function is called again | The new value |
The counter that the synchronization lesson protected with a synchronized block looks like this with AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounterExample {
private static final AtomicInteger count = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count.incrementAndGet();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("count = " + count.get());
}
} count = 200000 Three calls show how CAS works:
AtomicInteger value = new AtomicInteger(5);
System.out.println(value.compareAndSet(5, 10)); // expected 5, it was 5
System.out.println(value.compareAndSet(5, 20)); // expected 5, it is already 10
System.out.println(value.get()); true
false
10 Any operation on a single variable can be made atomic with a CAS loop: read the value, compute the new one, try to write it. If another thread changed the variable between the read and the write, compareAndSet returns false and the loop runs again with the fresh value.
int current, next;
do {
current = value.get();
next = current * 2;
} while (!value.compareAndSet(current, next));
// the same thing in one line
value.updateAndGet(x -> x * 2); This leads to a requirement that's easy to overlook: the function passed to updateAndGet may run several times, so it must have no side effects, such as printing to the console, writing to a database, or changing other fields.
A thread that loses a CAS doesn't go to sleep; it retries immediately, so under moderate contention atomic classes are usually faster than synchronized. When many threads hammer the same counter all the time, the retries start eating CPU time. For that kind of counter Java 8 added LongAdder, which spreads the sum across several cells and adds them up when you read it.
Thread-Safe Collections in Java
Thread-safe collections in Java come in three kinds: legacy synchronized classes (Vector, Hashtable), the synchronized wrappers Collections.synchronizedList/Set/Map, and the collections in java.util.concurrent (ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentLinkedQueue, BlockingQueue implementations). New code uses the third group. The regular ArrayList, HashMap and HashSet from the Collections Framework are not thread-safe.
| Collection | How thread safety is achieved | Iterating while it changes | When to use it |
|---|---|---|---|
Vector, Hashtable | Every method is synchronized on this (since Java 1.0) | Can throw ConcurrentModificationException | Legacy code only; not formally @Deprecated, but outdated |
Collections.synchronizedList(…), synchronizedMap(…) | A wrapper with one lock for the whole collection | Needs manual synchronized (list), otherwise ConcurrentModificationException | You need to make an existing collection thread-safe quickly, and the load is light |
ConcurrentHashMap | Locks on individual bins plus CAS; reads don't block | Weakly consistent iterator: no exceptions, may miss the latest changes | The default thread-safe map: caches, counters, registries |
CopyOnWriteArrayList | Every modification copies the whole internal array | The iterator works on a snapshot taken when it was created, no exceptions | Frequent reads, rare writes: listener lists, configuration |
ConcurrentLinkedQueue | A non-blocking queue built on CAS | Weakly consistent iterator | A task queue without waiting: poll() returns null when empty |
BlockingQueue (ArrayBlockingQueue, LinkedBlockingQueue) | Locks inside; put() waits for space, take() waits for data | Weakly consistent iterator | Producer-consumer (example) |
The key difference between a synchronized wrapper and ConcurrentHashMap is lock granularity. Collections.synchronizedMap puts one lock on the entire map: while one thread writes, everyone else waits, even threads reading a different key. ConcurrentHashMap locks only the bin being modified, so threads working with different keys barely get in each other's way.
A wrapper protects individual calls, not iteration. An iterator makes many calls in a row, and another thread can modify the list between them, so the Collections.synchronizedList documentation requires you to hold the list's own monitor for the entire traversal:
List<String> list = Collections.synchronizedList(new ArrayList<>());
synchronized (list) { // the monitor of the wrapper, not of the underlying ArrayList
for (String s : list) {
System.out.println(s);
}
} ConcurrentHashMap and CopyOnWriteArrayList don't have this problem: their iterators are designed for concurrent modification. The price of CopyOnWriteArrayList is copying the array on every add() and remove(); on a list of 100,000 elements that changes in a loop, it adds up quickly. How concurrent collections work internally and how to choose between them will get a lesson of its own.
Swapping HashMap for ConcurrentHashMap isn't always drop-in
ConcurrentHashMap accepts null neither as a key nor as a value: put(null, …) and put(key, null) throw NullPointerException. The reason: in a concurrent map, get(key) == null has to mean "no such key" unambiguously, otherwise the answer could change between get() and containsKey(). If old code stored null in a HashMap, it will fail after the swap.
A Thread-Safe Set in Java
The JDK has no separate ConcurrentHashSet. You get a thread-safe set in one of these ways:
Set<String> a = ConcurrentHashMap.newKeySet(); // Java 8, the default choice
Set<String> b = new CopyOnWriteArraySet<>(); // few elements, rare changes
Set<String> c = new ConcurrentSkipListSet<>(); // sorted, like TreeSet
Set<String> d = Collections.synchronizedSet(new HashSet<>()); // wrapper with a single lock ConcurrentHashMap.newKeySet() is a set backed by the keys of a ConcurrentHashMap, with the same properties: per-bin locking, an iterator that doesn't throw, and no null.
Thread-Safe Class ≠ Thread-Safe Code
A thread-safe class guarantees that each individual call is atomic, but not a sequence of calls. "Check, then act" (check-then-act) or "read, modify, write" code built from several methods of a thread-safe collection is still a race: another thread can change the object between the calls.
Even if a class is thread-safe, it's dangerous to rely on it to protect your data. In a thread-safe class each individual method is synchronized (or protected some other way). But nothing stops another thread from modifying an object of a thread-safe class between calls to its synchronized methods.
What does this code print?
import java.util.concurrent.ConcurrentHashMap;
public class MapCheckThenAct {
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
Integer old = counts.get("java"); // call 1
counts.put("java", old == null ? 1 : old + 1); // call 2
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("java = " + counts.get("java"));
}
} java = 104967 The number changes from run to run and is almost never 200,000. get() and put() are each safe on their own, but both threads can read 41 and both write 42: exactly the same lost update as count++ on a plain field. The fix is one atomic map operation instead of two:
counts.merge("java", 1, Integer::sum); // add 1, or put 1 if the key is absent java = 200000 Caches hit the same bug. The code below may call an expensive load() twice, and the second thread overwrites the value of the first:
// race: between containsKey and put another thread does the same thing
if (!cache.containsKey(key)) {
cache.put(key, load(key));
}
// atomic: load is called at most once per key
Value v = cache.computeIfAbsent(key, k -> load(k));
// if the value is already computed and there's nothing to load
Value previous = cache.putIfAbsent(key, value); // null means our value was stored The function in computeIfAbsent runs while the key is locked, so keep it short and don't touch other keys of the same map from inside it. Otherwise other threads wait, and a recursive update of the map can end with IllegalStateException.
The legacy synchronized classes behave the same way. In Vector, both isEmpty() and remove(0) are synchronized, but the pair isn't:
if (!vector.isEmpty()) {
String first = vector.remove(0); // ArrayIndexOutOfBoundsException if another thread
} // has already taken the last element
synchronized (vector) { // Vector's methods are synchronized on this,
if (!vector.isEmpty()) { // so a block on vector makes the pair atomic
String first = vector.remove(0);
}
} The block version works only because Vector locks on its own monitor. For ConcurrentHashMap the same trick is useless, since it uses internal locks. For queues, the better choice is a collection with a ready-made atomic operation: ConcurrentLinkedQueue.poll() checks for emptiness and takes the element in one step. The same rule applies to StringBuffer: each append() is synchronized, but a string assembled by two threads from several append() calls comes out interleaved.
StringBuilder vs StringBuffer, ArrayList vs Vector, HashMap vs ConcurrentHashMap
In each pair the first class is not thread-safe and is faster in a single thread, while the second is synchronized. Interviewers ask about this all the time, and the right answer is usually not "use the synchronized one" but "a regular class in a single thread, a class from java.util.concurrent for shared access".
| Not thread-safe | Thread-safe counterpart | Differences | What to choose |
|---|---|---|---|
StringBuilder | StringBuffer | Same API; every StringBuffer method is synchronized | StringBuilder: a string is almost always built by one thread |
ArrayList | Vector, Collections.synchronizedList, CopyOnWriteArrayList | Vector doubles in size when it grows, ArrayList grows by 1.5x; Vector is synchronized as a whole | ArrayList in a single thread; CopyOnWriteArrayList for frequent reads from many threads |
HashMap | Hashtable, Collections.synchronizedMap, ConcurrentHashMap | HashMap allows one null key and null values; Hashtable and ConcurrentHashMap don't (NullPointerException) | HashMap in a single thread; ConcurrentHashMap for shared access; Hashtable only in legacy code |
The synchronized StringBuffer, Vector and Hashtable appeared in Java 1.0, when there was nothing else. Since Java 1.2 their unsynchronized replacements have been the main choice, and Java 5 brought java.util.concurrent, where thread safety is designed more carefully than "a lock on every method". Synchronizing each method still doesn't save compound operations, so the old classes give a feeling of protection that isn't really there.
The @ThreadSafe, @NotThreadSafe and @GuardedBy Annotations
The @ThreadSafe, @NotThreadSafe, @Immutable and @GuardedBy annotations document how a class behaves in a multithreaded environment. They are not part of the JDK: they come from Brian Goetz's book "Java Concurrency in Practice" and are added as a separate library. On their own they synchronize nothing; they are a convention for people reading the code and for static analyzers.
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
@ThreadSafe
public class Counter {
@GuardedBy("this") // the field is read and written only under the monitor of this
private int count;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
} The original package is net.jcip.annotations (Maven artifact net.jcip:jcip-annotations). The same names exist in javax.annotation.concurrent from the com.google.code.findbugs:jsr305 library. If you want compile-time checks, use Error Prone: it verifies @GuardedBy, turning access to a field without the named monitor into a build error, and has its own com.google.errorprone.annotations.ThreadSafe and @Immutable annotations.
Even without an analyzer, @GuardedBy pays off: it writes down in the code what's usually kept in someone's head, namely which monitor protects the field. When someone adds a new method to the class a year later, the annotation tells them that count must not be read without synchronized (the reason is in synchronized and visibility).
Frequently Asked Questions
String is thread-safe, so does a field of type String need no synchronization?
It still needs it. What's immutable is the String object, not the variable that points to it. name = name + "!" creates a new string and reassigns the field, which is a read plus a write, and two threads can lose each other's update. Make the field final, volatile (if you need only visibility), an AtomicReference<String>, or guard it with synchronized.
Can several threads read a HashMap if nobody modifies it?
Yes, provided the map is fully populated before other threads see it and is safely published: for example, it's created before start() is called on those threads, or stored in a final field. After that, concurrent get() calls are safe. It's more reliable to make an unmodifiable copy right away with Map.copyOf(map): then an accidental write throws UnsupportedOperationException instead of corrupting the data.
Are local variables thread-safe?
The variables themselves are: each thread runs the method on its own stack and has its own copy. But if a local variable refers to an object that another thread can see (captured by a lambda passed to new Thread(…), stored in a shared field or collection), the object itself is shared and needs protection, as described in How to Make a Class Thread-Safe.
How do you check that a class is really thread-safe?
A test can't prove it: a race may stay hidden for a thousand runs and show up on a server under load. It's more reliable to review the code against the rules: which fields are mutable, which monitor guards each of them, and whether there are compound operations made of several calls. For stress testing, OpenJDK has the jcstress tool, which runs code fragments in different threads millions of times and reports every result it observed.
Comments