Java Thread Safety
Java thread safety means that a class or method keeps working correctly when many threads use it at the same time, without the callers having to add any extra locking. Code that is not thread-safe can lose updates, throw strange exceptions, or return corrupted data, but only sometimes, which makes the bugs hard to find.
Thread safety problems only appear when threads share mutable state: data that more than one thread can change. This lesson shows the main techniques for making code thread-safe, from simply not sharing data to using Java's concurrent classes.
What Breaks Java Thread Safety
Most standard classes, such as ArrayList and HashMap, are not thread-safe. They are fast because they do no locking, but they assume only one thread changes them at a time.
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<Integer> orderIds = new ArrayList<>(); // ArrayList is NOT thread-safe
Runnable addOrders = () -> {
for (int i = 0; i < 100_000; i++) {
try {
orderIds.add(i);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(Thread.currentThread().getName() + ": " + e.getClass().getSimpleName());
return;
}
}
};
Thread t1 = new Thread(addOrders, "t1");
Thread t2 = new Thread(addOrders, "t2");
Thread t3 = new Thread(addOrders, "t3");
t1.start(); t2.start(); t3.start();
t1.join(); t2.join(); t3.join();
System.out.println("expected size: 300000");
System.out.println("actual size : " + orderIds.size());
}
}
Output (different on every run; sometimes an ArrayIndexOutOfBoundsException is printed too):
expected size: 300000
actual size : 263281
How it works:
- Three threads each add 100,000 numbers to the same
ArrayList. add()stores the element and then increases an internalsizefield. When two threads do this at the same moment, they can write into the same slot, and one element is lost.- If the list grows its internal array while another thread is writing, that thread can even get an
ArrayIndexOutOfBoundsException.
| Thread-safety technique | Idea | Example tools |
|---|---|---|
| Confinement | Don't share the data at all | Local variables, ThreadLocal |
| Immutability | Share data that can't change | record, final fields, List.of() |
| Locking | Let one thread at a time change it | synchronized, ReentrantLock |
| Atomic variables | Lock-free single-value updates | AtomicInteger, LongAdder |
| Concurrent collections | Thread-safe data structures | ConcurrentHashMap, CopyOnWriteArrayList |
| Visibility | Make writes visible to other threads | volatile |
Locking was covered in Java Synchronization. The sections below cover the other techniques.
Thread Confinement: Don't Share the Data
The simplest way to be thread-safe is to keep data inside one thread. Local variables live on each thread's own stack, so two threads running the same method never see each other's locals.
import java.util.ArrayList;
import java.util.List;
public class Confinement {
// No shared fields: every call works only with its own local variables
static double cartTotal(List<Double> prices) {
double total = 0; // local: each thread has its own copy
List<String> lines = new ArrayList<>(); // created and used by one thread only
for (double price : prices) {
total += price;
lines.add(String.format("%.2f", price));
}
return total;
}
public static void main(String[] args) throws InterruptedException {
double[] results = new double[2];
Thread customerA = new Thread(() -> results[0] = cartTotal(List.of(199.0, 49.5, 20.0)));
Thread customerB = new Thread(() -> results[1] = cartTotal(List.of(999.0, 1.0)));
customerA.start();
customerB.start();
customerA.join();
customerB.join();
System.out.println("customer A total: " + results[0]);
System.out.println("customer B total: " + results[1]);
}
}
Output:
customer A total: 268.5
customer B total: 1000.0
How it works:
cartTotal()has no fields;totalandlinesare local variables.- Both threads run the same method at the same time, but each has its own
totaland its ownlineslist, so there is nothing to protect. - Each thread writes to a different slot of
results, andmainreads them afterjoin(), which makes the values visible.
Note: Confinement breaks as soon as a local object "escapes", for example when you store it in a static field or pass it to another thread. The rule is about who can reach the object, not where it was declared.
Immutable Objects Are Thread-Safe
An immutable object cannot change after it is created. Any number of threads can read it at the same time with no locking at all. In Java, a record with immutable field types is the easiest way to create one.
import java.util.List;
public class ImmutablePrice {
// A record is immutable: final fields, no setters
record Price(String sku, long amountPaise, String currency) {
Price withDiscount(int percent) {
// "Changing" an immutable object returns a NEW object
return new Price(sku, amountPaise * (100 - percent) / 100, currency);
}
}
public static void main(String[] args) throws InterruptedException {
Price original = new Price("HEADPHONES-01", 250_000, "INR");
List<Integer> discounts = List.of(10, 25, 50);
Price[] discounted = new Price[discounts.size()];
Thread[] workers = new Thread[discounts.size()];
for (int i = 0; i < workers.length; i++) {
int index = i;
// All threads read the same object; nobody can modify it
workers[i] = new Thread(() -> discounted[index] = original.withDiscount(discounts.get(index)));
workers[i].start();
}
for (Thread w : workers) w.join();
System.out.println("original: " + original);
for (Price p : discounted) System.out.println("new : " + p);
}
}
Output:
original: Price[sku=HEADPHONES-01, amountPaise=250000, currency=INR]
new : Price[sku=HEADPHONES-01, amountPaise=225000, currency=INR]
new : Price[sku=HEADPHONES-01, amountPaise=187500, currency=INR]
new : Price[sku=HEADPHONES-01, amountPaise=125000, currency=INR]
How it works:
Priceis a record, so its fields arefinaland it has no setters.withDiscount()does not modify the object; it returns a newPrice.- Three threads use the same
originalobject at once, and it is still unchanged at the end. - Strings,
LocalDate,BigDecimaland the lists made byList.of()are immutable too, which is why they can be shared freely.
Atomic Variables for Thread-Safe Counters
The classes in java.util.concurrent.atomic update a single value safely without a lock. They use special CPU instructions that read, change and write the value in one indivisible step.
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
public class AtomicCounter {
public static void main(String[] args) throws InterruptedException {
AtomicInteger pageViews = new AtomicInteger(); // one atomic counter
LongAdder apiCalls = new LongAdder(); // faster under heavy contention
Runnable visitor = () -> {
for (int i = 0; i < 250_000; i++) {
pageViews.incrementAndGet(); // atomic read-add-write, no lock
apiCalls.increment();
}
};
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(visitor);
threads[i].start();
}
for (Thread t : threads) t.join();
System.out.println("page views: " + pageViews.get());
System.out.println("api calls : " + apiCalls.sum());
}
}
Output:
page views: 1000000
api calls : 1000000
How it works:
incrementAndGet()is the atomic version ofcount++. Four threads add a quarter of a million each, and no update is lost.LongAdderspreads the counting over several internal cells, so it is faster when many threads update it constantly.sum()adds the cells together.- Use
AtomicIntegerwhen you need the new value immediately (like generating IDs), andLongAdderfor statistics that are read now and then.
Thread-Safe Collections in Java
The java.util.concurrent package offers collections built for multithreaded use. The older Collections.synchronizedList() wrapper also works, by locking every method.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class SafeCollections {
public static void main(String[] args) throws InterruptedException {
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
List<Integer> cowList = new CopyOnWriteArrayList<>();
Map<String, Integer> salesByCity = new ConcurrentHashMap<>();
String[] cities = {"Chennai", "Mumbai", "Delhi"};
Runnable task = () -> {
for (int i = 0; i < 3_000; i++) {
syncList.add(i);
if (i % 100 == 0) cowList.add(i); // fewer writes: copy-on-write is costly
salesByCity.merge(cities[i % 3], 1, Integer::sum); // atomic update per key
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
Thread t3 = new Thread(task);
t1.start(); t2.start(); t3.start();
t1.join(); t2.join(); t3.join();
System.out.println("synchronizedList size: " + syncList.size());
System.out.println("CopyOnWriteArrayList : " + cowList.size());
System.out.println("sales by city : " + new java.util.TreeMap<>(salesByCity));
}
}
Output:
synchronizedList size: 9000
CopyOnWriteArrayList : 90
sales by city : {Chennai=3000, Delhi=3000, Mumbai=3000}
How it works:
Collections.synchronizedList()wraps anArrayListand locks it for each call, so all 9000 additions are kept.CopyOnWriteArrayListcopies its internal array on every write. Writes are slow, but reads need no locking, which suits lists that are read often and changed rarely, such as a list of listeners.ConcurrentHashMap.merge()updates the count for a key atomically, so no sale is lost even though three threads update the same three keys.
| Collection | Thread-safe? | Best for |
|---|---|---|
ArrayList, HashMap, HashSet | No | One thread, or data that is never changed after setup |
Collections.synchronizedList/Map | Yes, one lock for everything | Simple cases with low traffic |
ConcurrentHashMap | Yes, fine-grained | Shared maps and caches |
CopyOnWriteArrayList | Yes | Many reads, very few writes |
ConcurrentLinkedQueue, ArrayBlockingQueue | Yes | Passing work between threads |
Check-Then-Act: Thread-Safe Classes Can Still Be Misused
Using a thread-safe collection does not make combinations of calls safe. "Check if the key is missing, then put it" is two separate calls, and another thread can act between them.
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class CheckThenAct {
static final AtomicInteger expensiveLoads = new AtomicInteger();
static String loadProfile(String userId) {
expensiveLoads.incrementAndGet(); // count how often the slow load runs
try {
Thread.sleep(50); // simulate a database call
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Profile of " + userId;
}
static void run(String label, Map<String, String> cache, boolean atomic) throws InterruptedException {
expensiveLoads.set(0);
CountDownLatch startSignal = new CountDownLatch(1);
Thread[] requests = new Thread[8];
for (int i = 0; i < requests.length; i++) {
requests[i] = new Thread(() -> {
try {
startSignal.await(); // all threads start at the same moment
} catch (InterruptedException e) {
return;
}
if (atomic) {
cache.computeIfAbsent("u42", CheckThenAct::loadProfile);
} else {
if (!cache.containsKey("u42")) { // check...
cache.put("u42", loadProfile("u42")); // ...then act: two separate steps
}
}
});
requests[i].start();
}
startSignal.countDown();
for (Thread r : requests) r.join();
System.out.println(label + " -> profile loaded " + expensiveLoads.get() + " time(s)");
}
public static void main(String[] args) throws InterruptedException {
run("containsKey + put ", new ConcurrentHashMap<>(), false);
run("computeIfAbsent ", new ConcurrentHashMap<>(), true);
}
}
Output:
containsKey + put -> profile loaded 8 time(s)
computeIfAbsent -> profile loaded 1 time(s)
How it works:
- A
CountDownLatchreleases all eight request threads at the same moment. - With
containsKey()followed byput(), every thread checks before any thread has stored the profile, so all eight run the slow database load. computeIfAbsent()does the check and the insert as one atomic step for that key. Only the first thread runsloadProfile; the others wait and receive the stored value.- The same problem exists with
if (counter.get() < limit) counter.incrementAndGet();. Prefer single methods that do the whole job, such ascompute,merge,putIfAbsentorcompareAndSet.
The volatile Keyword for Visibility
Each thread may keep its own cached copy of a variable for speed. Without synchronization, a change made by one thread might never be seen by another. Marking a field volatile guarantees that every read sees the most recent write.
public class VolatileFlag {
// volatile: every read sees the latest write from any thread
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread heartbeat = new Thread(() -> {
long beats = 0;
while (running) { // re-reads the field on every loop
beats++;
}
System.out.println("heartbeat: stopped after seeing running = false");
}, "heartbeat");
heartbeat.start();
Thread.sleep(500);
running = false; // this write becomes visible to heartbeat
heartbeat.join(2000);
System.out.println("main: heartbeat alive? " + heartbeat.isAlive());
}
}
Output:
heartbeat: stopped after seeing running = false
main: heartbeat alive? false
How it works:
heartbeatloops whilerunningistrue.mainsets it tofalseafter 500 ms.- Because
runningisvolatile,heartbeatreads the real current value on each loop and stops. Withoutvolatile, the JIT compiler is allowed to read the field once and loop forever. volatileguarantees visibility, not atomicity:volatileCount++is still unsafe. Use it for simple flags and for publishing a reference that is written by one thread.
Thread-Safe and Unsafe JDK Classes
Some JDK classes look harmless but are not thread-safe, because they keep changing internal state while they work. Sharing one instance between threads gives wrong results or exceptions; the usual fix is a thread-safe alternative or one instance per thread.
| Not thread-safe | Thread-safe alternative |
|---|---|
SimpleDateFormat | DateTimeFormatter (immutable) |
StringBuilder (when shared) | Local StringBuilder per thread, or StringBuffer |
HashMap | ConcurrentHashMap |
Random (shared, slow under contention) | ThreadLocalRandom.current() |
NumberFormat, DecimalFormat | One instance per thread (ThreadLocal) |
Giving Each Thread Its Own Copy with ThreadLocal
When a class is not thread-safe but expensive to create, ThreadLocal gives every thread its own instance. That is thread confinement handled for you.
import java.text.NumberFormat;
import java.util.Locale;
public class ThreadLocalDemo {
// Each thread gets its own NumberFormat instance (NumberFormat is not thread-safe)
private static final ThreadLocal<NumberFormat> RUPEES =
ThreadLocal.withInitial(() -> NumberFormat.getCurrencyInstance(Locale.of("en", "IN")));
public static void main(String[] args) throws InterruptedException {
NumberFormat[] seen = new NumberFormat[2];
Thread a = new Thread(() -> {
seen[0] = RUPEES.get(); // created on the first get() in this thread
System.out.println("invoice-a: " + seen[0].format(123456.5));
System.out.println("invoice-a: same instance on second get()? " + (RUPEES.get() == seen[0]));
}, "invoice-a");
Thread b = new Thread(() -> {
seen[1] = RUPEES.get(); // a separate instance for this thread
System.out.println("invoice-b: " + seen[1].format(999.0));
}, "invoice-b");
a.start(); a.join();
b.start(); b.join();
System.out.println("threads share one formatter? " + (seen[0] == seen[1]));
}
}
Output:
invoice-a: ₹123,456.50
invoice-a: same instance on second get()? true
invoice-b: ₹999.00
threads share one formatter? false
How it works:
ThreadLocal.withInitial()creates a newNumberFormatthe first time each thread callsget().- Within one thread,
get()always returns the same instance; different threads get different instances, so they can never interfere. - In thread pools, threads are reused for many tasks. Call
RUPEES.remove()when a task's per-thread data must not leak into the next task.
Real-World Example: A Thread-Safe Inventory Service
This inventory service combines several techniques: immutable products, an unchangeable catalog map, an atomic stock update per product, an atomic order counter, a LongAdder for revenue and a concurrent list for alerts. Eight customer threads order at the same time, and the stock must never go below zero.
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
public class InventoryService {
// Immutable value object: safe to share between threads
record Product(String sku, String name, long pricePaise) { }
// Immutable result object
record OrderResult(String orderId, boolean accepted, String reason) { }
private final Map<String, Product> catalog; // never changed after construction
private final ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>();
private final AtomicInteger orderSequence = new AtomicInteger(1000);
private final LongAdder revenuePaise = new LongAdder();
private final List<String> soldOutAlerts = new CopyOnWriteArrayList<>();
InventoryService(List<Product> products, int initialStock) {
catalog = Map.copyOf(products.stream()
.collect(java.util.stream.Collectors.toMap(Product::sku, p -> p)));
for (Product p : products) {
stock.put(p.sku(), initialStock);
}
}
OrderResult placeOrder(String sku, int quantity) {
String orderId = "ORD-" + orderSequence.incrementAndGet();
Product product = catalog.get(sku);
if (product == null) {
return new OrderResult(orderId, false, "unknown product");
}
boolean[] reserved = {false};
// compute() runs atomically for this key: check and update happen together
stock.compute(sku, (key, available) -> {
if (available >= quantity) {
reserved[0] = true;
int left = available - quantity;
if (left == 0) soldOutAlerts.add(key);
return left;
}
return available; // not enough stock: keep the value unchanged
});
if (!reserved[0]) {
return new OrderResult(orderId, false, "out of stock");
}
revenuePaise.add(product.pricePaise() * quantity);
return new OrderResult(orderId, true, "ok");
}
public static void main(String[] args) throws InterruptedException {
InventoryService shop = new InventoryService(List.of(
new Product("PHONE", "Smartphone", 1_500_000),
new Product("CASE", "Phone case", 50_000)), 100);
LongAdder accepted = new LongAdder();
LongAdder rejected = new LongAdder();
Thread[] customers = new Thread[8];
for (int c = 0; c < customers.length; c++) {
customers[c] = new Thread(() -> {
for (int i = 0; i < 30; i++) {
String sku = (i % 2 == 0) ? "PHONE" : "CASE";
OrderResult result = shop.placeOrder(sku, 1);
if (result.accepted()) accepted.increment(); else rejected.increment();
}
});
customers[c].start();
}
for (Thread customer : customers) customer.join();
System.out.println("orders accepted : " + accepted.sum());
System.out.println("orders rejected : " + rejected.sum());
System.out.println("stock left : " + new java.util.TreeMap<>(shop.stock));
System.out.println("sold-out alerts : " + shop.soldOutAlerts);
System.out.printf("revenue : Rs. %,.2f%n", shop.revenuePaise.sum() / 100.0);
System.out.println("last order id : ORD-" + shop.orderSequence.get());
}
}
Output:
orders accepted : 200
orders rejected : 40
stock left : {CASE=0, PHONE=0}
sold-out alerts : [PHONE, CASE]
revenue : Rs. 1,550,000.00
last order id : ORD-1240
How it works:
- Immutable data.
ProductandOrderResultare records, andcatalogis created withMap.copyOf(), so it can be read by all threads with no locking. - Atomic stock check.
stock.compute(sku, ...)checks the available quantity and stores the new quantity in one atomic step for that product. Two customers can never both take the last phone. - Unique order IDs.
AtomicInteger.incrementAndGet()gives every order a different number, fromORD-1001toORD-1240. - Revenue and alerts.
LongAdderadds up revenue from many threads cheaply, andCopyOnWriteArrayListcollects the rarely written sold-out alerts. The sold-out order (PHONEorCASEfirst) can differ between runs. - The proof. 8 customers × 30 orders = 240 orders. Exactly 200 are accepted (100 phones + 100 cases), 40 are rejected as out of stock, the stock ends at exactly 0, and the revenue is 100 × Rs. 15,000 + 100 × Rs. 500 = Rs. 1,550,000.
To see how the customer threads are started and awaited, revisit Java Thread Join and Java Runnable Interface.