Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
kvi5hnuCode Sprout team member14 min readOn this page
Locks are not the only way to share data correctly between threads. For a single flag, a counter or a lazily created singleton, a full lock is often more than you need, and there are lighter, faster tools. This article explains why unsynchronized sharing goes wrong (memory visibility), then covers volatile, final fields, the atomic classes, LongAdder, on-demand initialization and safe publication. It ends with two ways to avoid problems: never creating a lock cycle (deadlock) and never sharing at all (ThreadLocal).
Why unsynchronized reads can be wrong
It's tempting to think that reading or writing one field can't go wrong. On modern hardware and compilers it can:
- Caches and registers. Each CPU core keeps values in registers and local caches. A thread on one core may keep reading a stale copy while another core has written a new value.
- Reordering. Compilers, the JIT and the CPU reorder instructions for speed. They keep the meaning of single-threaded code, assuming memory only changes when this thread's code changes it. Another thread can break that assumption.
Locks fix both problems. Acquiring and releasing a lock forces the JVM to flush or re-read values, prevents harmful reordering, and issues memory fences. The precise rules are the Java Memory Model (JLS §17.4), built on the happens-before relation. Everything a thread did before releasing a lock is visible to the next thread that acquires it. Brian Goetz summarized it as a rule worth memorizing: if you write a variable that another thread may read next, or read a variable another thread may have written last, you must synchronize.
volatile fields
volatile is a lock-free way to synchronize access to one field. The compiler and JVM guarantee that a write to a volatile field is visible to every later read of it by any thread, and writes made before the volatile write become visible along with it. A classic use is a stop flag set by one thread and polled by another:
private volatile boolean done;
public boolean isDone() { return done; }
public void setDone() { done = true; }
Without volatile, the JIT may hoist the read out of a while (!done) loop, and the worker can spin forever. Using synchronized getters and setters also works, but they can block when another thread holds the object's lock.
final fields
A third safe case is final fields. Once a constructor completes, every thread that gets a reference to the object sees its final fields with their initialized values:
public class Bank {
final HashMap<String, Double> accounts;
public Bank() { accounts = new HashMap<>(); }
}
Without final, another thread might see accounts as null. This guarantees only that the reference is visible. Operations on the map are still not thread-safe.
The guarantee has one condition: this must not escape during construction. If the constructor stores this in a static field, registers it as a listener, or starts a thread that uses it, another thread may see a half-built object. An object is properly constructed if this doesn't escape. A properly constructed object whose fields are all final, holding immutable data, is immutable and can be shared freely without synchronization. Records with immutable components are the easiest way to get this.
Atomics
The java.util.concurrent.atomic package uses machine-level instructions, mainly compare-and-set (CAS), to make operations atomic without locks.
public static final AtomicLong nextNumber = new AtomicLong();
// in any thread:
long id = nextNumber.incrementAndGet();
incrementAndGet reads, adds 1, stores and returns the new value as one indivisible step. No two threads ever get the same id.
For more complex updates, don't combine get and set. That is a race:
largest.set(Math.max(largest.get(), observed)); // NOT atomic
Instead, pass the update as a function and let the class retry it until it succeeds:
largest.updateAndGet(x -> Math.max(x, observed));
largest.accumulateAndGet(observed, Math::max);
getAndUpdate and getAndAccumulate return the old value instead. Underneath, these methods run a CAS loop. They read the current value, compute the new one, and call compareAndSet(old, new), which stores only if the value is still old. If another thread changed it in the meantime, they try again. That's why the function you pass must be free of side effects, because it may run more than once.
The same methods exist in AtomicInteger, AtomicReference, the array versions AtomicIntegerArray, AtomicLongArray and AtomicReferenceArray, and the field updaters AtomicIntegerFieldUpdater and friends. For new low-level code, VarHandle (Java 9) offers the same atomic operations on ordinary fields and array elements. AtomicBoolean and AtomicReference.compareAndSet are handy for "do this only once" flags.
LongAdder and LongAccumulator
With many threads hammering one AtomicLong, CAS operations fail and retry constantly, and performance collapses. A LongAdder spreads the count over several internal cells. Threads update different cells, cells are added as contention grows, and the total is computed only when you ask for it. If you expect high contention and only need the total at the end, use LongAdder instead of AtomicLong:
var adder = new LongAdder();
// in many tasks:
adder.increment(); // or add(n)
// at the end:
long total = adder.sum();
increment deliberately returns nothing. Returning the current total would require combining all cells and lose the benefit. Note that sum() is not an atomic snapshot while updates are still in progress.
LongAccumulator generalizes this to any operation. You supply the operation and its neutral element:
var max = new LongAccumulator(Math::max, Long.MIN_VALUE);
max.accumulate(value); // in many threads
long result = max.get();
Each cell starts at the neutral element. accumulate(v) atomically updates one cell to aᵢ = aᵢ op v, and get() returns a₁ op a₂ op … op aₙ. The operation must be associative and commutative, because the order of combination is unpredictable. new LongAccumulator(Long::sum, 0) behaves like a LongAdder. DoubleAdder and DoubleAccumulator do the same for double.
On-demand initialization
To create something lazily, exactly once, on first use, don't write your own double-checked locking. The JVM already runs a class's static initializer exactly once, the first time the class is used, under an internal lock. The holder idiom relies on that:
public class OnDemandData {
private OnDemandData() { ... }
public static OnDemandData getInstance() {
return Holder.INSTANCE;
}
private static class Holder { // loaded on the first call to getInstance
static final OnDemandData INSTANCE = new OnDemandData();
}
}
There's no locking on later calls, and the result is safely published. One caution: the constructor must not throw. If initialization fails, the JVM won't try again, and every later use of the holder throws NoClassDefFoundError. A single-element enum is another good singleton. If you do need lazy instance fields, double-checked locking works only when the field is volatile.
Safe publication
Final fields are covered. What about non-final fields of an object that one thread creates and another uses? In general Java guarantees nothing. Another thread may see a new BankAccount(1000) with getBalance() returning 0. Thread-safe classes avoid this by guarding their fields with locks. For an object that is neither thread-safe nor immutable, you need safe publication: every field set in the constructor must be visible to the receiving thread. That's guaranteed when the reference is stored
- in a static initializer,
- in a
volatilefield or anAtomicReference, - in any field, with the assignment and the read protected by the same lock, or
- in a
finalfield of a properly constructed object.
In practice, these often happen without any effort on your part. A lambda or inner class passed to an executor captures variables in final fields. A thread-safe collection such as BlockingQueue or ConcurrentHashMap publishes what you put into it. Thread.start, Thread.join and Future.get also create happens-before edges. If you find yourself depending on the fine print, rethink the design. Share immutable objects or hand data over through concurrent collections.
Deadlocks
Locks bring a new failure mode. A deadlock is a cycle of threads in which each waits for a lock held by the next. The classic case is two locks acquired in opposite orders:
// thread t1 // thread t2
synchronized (a) { synchronized (b) {
synchronized (b) { ... } synchronized (a) { ... }
} }
If t1 gets a and t2 gets b at the same moment, each waits forever for the other. Bank transfers do this naturally: transfer(1, 2) locks account 1 then 2, and transfer(2, 1) locks 2 then 1.

Java won't detect or break deadlocks for you. You avoid them by design:
- Lock ordering. Give locks a global order and always acquire them in that order. For example, lock the account with the smaller id first, whichever direction the money flows.
- Fewer, shorter locks. Don't call unknown code, such as listeners or overridable methods, while holding a lock, because it may take other locks.
- Timeouts. With
ReentrantLock.tryLock(time, unit), a thread that can't get the second lock releases the first and retries later. - Higher-level tools. Queues and concurrent collections hide the locking.
Deadlocks can also come from conditions, when every thread awaits and nobody signals (article 98). To diagnose a hung program, take a thread dump with jcmd <pid> Thread.print, jstack, or Ctrl+\ on Unix. The JVM prints "Found one Java-level deadlock" with the cycle. JConsole and VisualVM have a "Detect Deadlock" button. In code, ThreadMXBean.findDeadlockedThreads() returns the ids, which the demo uses.
Thread-local variables
The safest sharing is no sharing. A ThreadLocal<T> isn't really a variable. It's an object whose get and set methods read and write a value belonging to the current thread. Two uses are common.
1. One instance per thread of a non-thread-safe object. SimpleDateFormat corrupts its internal state when used concurrently. Synchronizing is slow, and creating one per call is wasteful. A thread-local gives each thread its own:
public static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
String stamp = DATE_FORMAT.get().format(new Date());
The supplier runs the first time a thread calls get, and later calls in that thread return the same instance. In modern code, use the immutable, thread-safe java.time.format.DateTimeFormatter, which needs no thread-local at all.
2. Task context without passing parameters. A transaction, a database connection, or the current user can be made available to every method that works on a task:
public static final ThreadLocal<Connection> CONNECTION = new ThreadLocal<>();
CONNECTION.set(connect(url, user, password)); // when the task starts
...
var result = CONNECTION.get().executeQuery(q); // deep inside some method
An InheritableThreadLocal copies the parent thread's value into each child thread when the child is created. Each child gets its own copy, because it might change the value.
Random numbers. java.util.Random is thread-safe, but threads contend on its shared seed. ThreadLocalRandom.current().nextInt(lo, hi) gives each thread its own generator, stored in the Thread object, and is the right choice in concurrent code.
Thread-locals, virtual threads and scoped values
With virtual threads there can be a million threads, and a million copies of a "per-thread" cache is a problem. Rethink expensive thread-local caches, and pool such objects explicitly if needed. The flag -Djdk.traceVirtualThreadLocals prints a stack trace when a virtual thread sets a thread-local.
Scoped values (java.lang.ScopedValue, preview in Java 21 to 24, final in Java 25 via JEP 506) are the modern replacement for passing context. A value is bound for the duration of a call, can't be changed, disappears automatically afterwards, and is inherited cheaply by subtasks of a StructuredTaskScope:
static final ScopedValue<Connection> CONNECTION = ScopedValue.newInstance();
ScopedValue.where(CONNECTION, connect(url, user, password))
.run(() -> doWork()); // bound only during this call
void doWork() {
var result = CONNECTION.get().executeQuery(q);
}
With virtual threads, prefer scoped values to thread-locals for passing context.
A complete example
The demo stops a worker with a volatile flag and counts from four threads with a lock and with AtomicInteger. It tracks a maximum with updateAndGet/accumulateAndGet, shows compareAndSet succeeding and failing, totals with LongAdder and LongAccumulator, and initializes lazily with a holder class. It publishes an array through a BlockingQueue, uses per-thread formatters, reproduces a ThreadLocal leak in a pool, and propagates an InheritableThreadLocal. Finally it creates a real lock-ordering deadlock (with daemon threads, so the program can still exit), detects it with ThreadMXBean, and fixes it with a consistent order.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Solution {
// 1. volatile flag
private static volatile boolean done;
// 2. on-demand initialization holder
static class Config {
private Config() { System.out.println(" Config constructor runs"); }
static Config getInstance() { return Holder.INSTANCE; }
private static class Holder {
static final Config INSTANCE = new Config();
}
}
// 3. thread-local values
static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(() -> {
var f = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f;
});
static final ThreadLocal<String> USER = new ThreadLocal<>();
static final InheritableThreadLocal<String> REQUEST_ID = new InheritableThreadLocal<>();
public static void main(String[] args) throws Exception {
System.out.println("-- volatile stop flag --");
var worker = new Thread(() -> {
while (!done) Thread.onSpinWait();
System.out.println(" worker saw done = true");
});
worker.start();
Thread.sleep(50);
done = true;
worker.join();
System.out.println("-- counting from 4 threads: lock vs atomic --");
var plain = new int[1];
var atomic = new AtomicInteger();
var pool = Executors.newFixedThreadPool(4);
var tasks = new ArrayList<Callable<Void>>();
for (int t = 0; t < 4; t++)
tasks.add(() -> {
for (int i = 0; i < 100_000; i++) {
synchronized (plain) { plain[0]++; }
atomic.incrementAndGet();
}
return null;
});
pool.invokeAll(tasks);
System.out.println(" synchronized count = " + plain[0] + ", atomic count = " + atomic.get());
System.out.println("-- atomic updates --");
var nextId = new AtomicLong();
System.out.println(" ids: " + nextId.incrementAndGet() + ", " + nextId.incrementAndGet() + ", " + nextId.incrementAndGet());
var largest = new AtomicLong(Long.MIN_VALUE);
var observations = new Random(42).longs(1000, 0, 1_000_000).toArray();
var obsTasks = new ArrayList<Callable<Void>>();
for (int t = 0; t < 4; t++) {
int start = t * 250;
obsTasks.add(() -> {
for (int i = start; i < start + 250; i++) {
long observed = observations[i];
if (i % 2 == 0) largest.updateAndGet(x -> Math.max(x, observed));
else largest.accumulateAndGet(observed, Math::max);
}
return null;
});
}
pool.invokeAll(obsTasks);
System.out.println(" largest = " + largest.get() + ", expected = " + Arrays.stream(observations).max().getAsLong());
var counter = new AtomicInteger(10);
System.out.println(" compareAndSet(10, 11): " + counter.compareAndSet(10, 11) + ", value " + counter.get());
System.out.println(" compareAndSet(10, 12): " + counter.compareAndSet(10, 12) + ", value " + counter.get());
System.out.println(" getAndAdd(5) returns " + counter.getAndAdd(5) + ", value " + counter.get());
System.out.println("-- LongAdder and LongAccumulator --");
var adder = new LongAdder();
var max = new LongAccumulator(Math::max, Long.MIN_VALUE);
var adderTasks = new ArrayList<Callable<Void>>();
for (int t = 0; t < 8; t++) {
int id = t;
adderTasks.add(() -> {
for (int i = 1; i <= 10_000; i++) {
adder.increment();
max.accumulate(id * 10_000L + i);
}
return null;
});
}
pool.invokeAll(adderTasks);
System.out.println(" adder.sum() = " + adder.sum() + ", max.get() = " + max.get());
System.out.println("-- on-demand initialization --");
System.out.println(" before first getInstance");
var c1 = Config.getInstance();
var c2 = Config.getInstance();
System.out.println(" same instance: " + (c1 == c2));
System.out.println("-- safe publication through a BlockingQueue --");
var queue = new ArrayBlockingQueue<int[]>(1);
var consumer = new Thread(() -> {
try {
int[] data = queue.take();
System.out.println(" consumer sees " + Arrays.toString(data));
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
consumer.start();
int[] data = {1, 2, 3};
data[2] = 30; // all writes happen before the put
queue.put(data);
consumer.join();
System.out.println("-- ThreadLocal: one formatter per thread --");
var formatters = Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<SimpleDateFormat, Boolean>()));
var dates = Collections.synchronizedList(new ArrayList<String>());
var fmtTasks = new ArrayList<Callable<Void>>();
for (int t = 0; t < 4; t++)
fmtTasks.add(() -> {
formatters.add(FORMAT.get());
formatters.add(FORMAT.get()); // same thread, same object
dates.add(FORMAT.get().format(new Date(0)));
return null;
});
pool.invokeAll(fmtTasks);
System.out.println(" formatted: " + new TreeSet<>(dates) + ", formatters created <= 4: " + (formatters.size() <= 4));
pool.shutdown();
System.out.println("-- ThreadLocal leak in a pool --");
var single = Executors.newSingleThreadExecutor();
single.submit(() -> USER.set("alice")).get(); // forgets remove()
System.out.println(" next task sees USER = " + single.submit(USER::get).get());
single.submit(() -> {
USER.set("bob");
try { /* work */ } finally { USER.remove(); }
}).get();
System.out.println(" after remove(), next task sees USER = " + single.submit(USER::get).get());
single.shutdown();
System.out.println("-- InheritableThreadLocal --");
USER.set("main-user");
REQUEST_ID.set("req-17");
var child = new Thread(() ->
System.out.println(" child: USER = " + USER.get() + ", REQUEST_ID = " + REQUEST_ID.get()));
child.start();
child.join();
System.out.println("-- ThreadLocalRandom --");
int r = ThreadLocalRandom.current().nextInt(1, 7);
System.out.println(" die roll in 1..6: " + (r >= 1 && r <= 6));
System.out.println("-- lock-ordering deadlock --");
Object a = new Object(), b = new Object();
var bothHoldFirst = new CountDownLatch(2);
Thread t1 = lockInOrder("t1", a, b, bothHoldFirst);
Thread t2 = lockInOrder("t2", b, a, bothHoldFirst);
t1.start(); t2.start();
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
long[] ids = null;
for (int i = 0; i < 200 && ids == null; i++) { Thread.sleep(10); ids = mx.findDeadlockedThreads(); }
var names = new TreeSet<String>();
if (ids != null) for (var info : mx.getThreadInfo(ids)) names.add(info.getThreadName() + " waits for lock held by " + info.getLockOwnerName());
names.forEach(n -> System.out.println(" " + n));
System.out.println(" t1 state: " + t1.getState() + ", t2 state: " + t2.getState());
System.out.println("-- fix: always lock in the same order --");
Object c = new Object(), d = new Object();
var noWait = new CountDownLatch(0);
Thread t3 = lockInOrder("t3", c, d, noWait);
Thread t4 = lockInOrder("t4", c, d, noWait); // same order: c, then d
t3.start(); t4.start(); t3.join(); t4.join();
System.out.println(" both finished: " + (t3.getState() == Thread.State.TERMINATED && t4.getState() == Thread.State.TERMINATED));
}
private static Thread lockInOrder(String name, Object first, Object second, CountDownLatch latch) {
var t = new Thread(() -> {
synchronized (first) {
latch.countDown();
try { latch.await(); } catch (InterruptedException e) { return; }
synchronized (second) { /* transfer */ }
}
}, name);
t.setDaemon(true); // so the deadlocked demo threads don't keep the JVM alive
return t;
}
}
-- volatile stop flag --
worker saw done = true
-- counting from 4 threads: lock vs atomic --
synchronized count = 400000, atomic count = 400000
-- atomic updates --
ids: 1, 2, 3
largest = 998981, expected = 998981
compareAndSet(10, 11): true, value 11
compareAndSet(10, 12): false, value 11
getAndAdd(5) returns 11, value 16
-- LongAdder and LongAccumulator --
adder.sum() = 80000, max.get() = 80000
-- on-demand initialization --
before first getInstance
Config constructor runs
same instance: true
-- safe publication through a BlockingQueue --
consumer sees [1, 2, 30]
-- ThreadLocal: one formatter per thread --
formatted: [1970-01-01], formatters created <= 4: true
-- ThreadLocal leak in a pool --
next task sees USER = alice
after remove(), next task sees USER = null
-- InheritableThreadLocal --
child: USER = null, REQUEST_ID = req-17
-- ThreadLocalRandom --
die roll in 1..6: true
-- lock-ordering deadlock --
t1 waits for lock held by t2
t2 waits for lock held by t1
t1 state: BLOCKED, t2 state: BLOCKED
-- fix: always lock in the same order --
both finished: true
Common questions
When is volatile enough?
When one thread writes a value and others only read it, as with a stop flag or a reference to a fully built immutable object. It isn't enough for read-modify-write operations such as count++. Use an atomic class or a lock for those.
AtomicLong or LongAdder?
Use LongAdder for counters that many threads update often, when you only read the total occasionally. Use AtomicLong when you need the current value from each update, such as for generating IDs, or a compare-and-set.
Is double-checked locking still broken?
It works if the field is volatile, which has been true since Java 5. For lazily created static singletons, the holder class idiom is simpler and needs no volatile or locking.
How do I find a deadlock in a running program?
Take a thread dump with jcmd <pid> Thread.print or jstack <pid>. The JVM detects cycles between monitors and java.util.concurrent locks and prints "Found one Java-level deadlock" with the threads and locks involved. JConsole and VisualVM can do the same.
Should I use ThreadLocal or ScopedValue?
For passing context such as the current user or request, use ScopedValue, which is final since Java 25: it's immutable, automatically scoped and cheap with virtual threads. ThreadLocal remains for per-thread caches of mutable objects, but always call remove() when a pool thread finishes a task.
API reference
java.util.concurrent.atomic.AtomicInteger / AtomicLong (similar methods in other atomic classes)
| Method | Description |
|---|---|
get(), set(v) | read or write the value with volatile semantics |
lazySet(v) / setRelease(v) | a weaker ordered write (release semantics only); rarely needed |
incrementAndGet(), decrementAndGet(), addAndGet(d) | atomic update; returns the new value |
getAndIncrement(), getAndDecrement(), getAndAdd(d), getAndSet(v) | atomic update; returns the old value |
boolean compareAndSet(expect, update) | sets to update only if the current value is expect |
updateAndGet(op), getAndUpdate(op) | applies a side-effect-free unary function atomically |
accumulateAndGet(x, op), getAndAccumulate(x, op) | combines the value with x using a binary operator |
LongAdder / LongAccumulator (java.util.concurrent.atomic)
| Method | Description |
|---|---|
void increment(), void decrement(), void add(long x) | LongAdder: updates one internal cell |
long sum(), void reset(), long sumThenReset() | LongAdder: combines the cells |
LongAccumulator(LongBinaryOperator op, long identity) | accumulator with an associative, commutative operation |
void accumulate(long x), long get() | adds a value; combines the cells |
java.lang.ThreadLocal<T> and related
| Method | Description |
|---|---|
static <S> ThreadLocal<S> withInitial(Supplier<? extends S> s) | thread-local whose initial value comes from s |
T get() | the current thread's value, initializing it on first use |
void set(T t), void remove() | sets or removes the current thread's value |
InheritableThreadLocal<T> | child threads start with a copy of the parent's value |
ThreadLocalRandom.current() | a random generator local to the current thread |
ThreadMXBean.findDeadlockedThreads() | ids of deadlocked threads, or null |
Summary
- Without synchronization, threads may see stale values or reordered writes. Locks,
volatile,finaland the concurrent classes create the happens-before edges that make writes visible. volatilesuits simple flags and assignments but never makes read-modify-write atomic. Final fields of properly constructed objects are visible to all threads.- Atomic classes give lock-free counters and CAS-based updates with side-effect-free functions. Use
LongAdderandLongAccumulatorunder heavy contention. - Use the holder idiom (or an enum) for lazy singletons. Publish mutable objects safely through static initializers, volatile or atomic references, locks, final fields or concurrent collections.
- Avoid deadlocks by locking in a global order, keeping critical sections small, using timeouts and preferring high-level tools. Diagnose them with thread dumps.
ThreadLocalgives each thread its own value. Alwaysremove()in pools. With virtual threads, preferScopedValue(final in Java 25).
Practice Questions
Why is "volatile int count; count++;" not thread-safe?
count++ reads the value, adds one and writes it back in three steps. volatile makes each read and write visible but doesn't make the sequence atomic, so two threads can read the same value and one increment is lost. Use AtomicInteger.incrementAndGet(), LongAdder or a lock.
When should you choose LongAdder over AtomicLong?
When many threads update the value frequently and you mostly need the total afterwards, as with statistics or hit counters. LongAdder spreads updates over cells to avoid CAS contention. If you need the new value back on every update, as with an id generator, use AtomicLong.
Why must the function passed to updateAndGet be free of side effects?
The method runs a compare-and-set loop. If another thread changes the value between the read and the CAS, the function is called again with the new value. A side effect such as printing or adding to a list could therefore happen several times.
Two threads transfer money between accounts 1 and 2 in opposite directions, each locking source then target. What can happen, and how do you fix it?
A deadlock. One thread holds account 1's lock and waits for account 2's, while the other holds account 2's and waits for account 1's. The fix is to always lock in a global order, such as the smaller account id first, or to use tryLock with a timeout and back off.
Why must a task running in a thread pool call remove() on its ThreadLocal values?
The pool reuses the thread, so the next task would see the stale value. That can leak data between tasks or users. The value also stays reachable and can't be garbage collected. Call remove() in a finally block.
Previous: Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Next: Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
Related reading
- Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
- Java Race Conditions and ReentrantLock: Synchronizing Shared Data
- Java Callable, Future and ExecutorService: Thread Pools and Task Results
- Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
- Java Thread States: New, Runnable, Blocked, Waiting and Terminated

More in Core Java I
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Java Callable, Future and ExecutorService: Thread Pools and Task Results
Run tasks that return results with Callable and Future, then let an ExecutorService manage threads: fixed, cached and single-thread pools, virtual-thread-per-task executors, get with timeouts, cancellation, Future.state and resultNow, closing executors, and throttling with semaphores.
Discussion
Sign in to ask a question or share what you learned.