Java Concurrency
Threads, synchronized and locks, wait/notify, executors and thread pools, Future and CompletableFuture, atomics, concurrent collections, synchronizers (CountDownLatch, Semaphore), and common bugs.
Java has had threads since 1.0 and a rich concurrency library (java.util.concurrent) since Java 5. This lesson is the practical toolkit; the why behind visibility and ordering is in Java memory model, and the general theory in Synchronization.
Threads
Thread t = new Thread(() -> System.out.println("hi from " + Thread.currentThread().getName()));
t.start(); // NOT run(): run() executes on the current thread
t.join(); // wait for it to finish
Thread v = Thread.ofVirtual().start(() -> work()); // Java 21 virtual threadThread states: NEW → RUNNABLE → (BLOCKED on a monitor / WAITING / TIMED_WAITING) → TERMINATED. In real code you rarely create threads directly — use executors.
The problem: race conditions
class Counter {
private int count = 0;
void increment() { count++; } // read, add, write: three steps, not atomic
}
// Two threads × 1,000,000 increments → often prints far less than 2,000,000synchronized
Every object has an intrinsic monitor lock. synchronized gives mutual exclusion and visibility (changes made inside are seen by the next thread to acquire the same lock).
class Counter {
private int count = 0;
public synchronized void increment() { count++; } // locks 'this'
public synchronized int get() { return count; } // reads need the lock too!
}
// Synchronized block: lock a private object, keep the critical section small
private final Object lock = new Object();
void add(Item i) {
var processed = expensiveTransform(i); // outside the lock
synchronized (lock) { items.add(processed); }
}Monitors are reentrant: a thread holding a lock can acquire it again (so synchronized methods can call each other).
wait / notify
Low-level condition waiting on a monitor — always in a loop (spurious wake-ups, and the condition may have changed):
synchronized (lock) {
while (queue.isEmpty()) lock.wait(); // releases the lock while waiting
return queue.poll();
}
// producer
synchronized (lock) { queue.add(x); lock.notifyAll(); }Prefer higher-level tools (BlockingQueue, Condition, latches) — they're easier to get right.
Explicit locks
java.util.concurrent.locks offers more control than synchronized:
private final ReentrantLock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();
void put(T x) {
lock.lock();
try { queue.add(x); notEmpty.signal(); }
finally { lock.unlock(); } // ALWAYS in finally
}
boolean tryTransfer() throws InterruptedException {
if (lock.tryLock(100, TimeUnit.MILLISECONDS)) { // timeout: avoids deadlock
try { ...; return true; } finally { lock.unlock(); }
}
return false;
}synchronized | ReentrantLock | ReadWriteLock | StampedLock | |
|---|---|---|---|---|
| Timeout / tryLock | No | Yes | Yes | Yes |
| Interruptible wait | No | lockInterruptibly | Yes | Yes |
| Multiple conditions | One per monitor | Many | Yes | — |
| Many readers at once | No | No | Yes | Yes, plus optimistic reads |
| Release | Automatic | Manual (finally) | Manual | Manual |
Executors and thread pools
Creating a thread per task is expensive (for platform threads) and unbounded. An executor reuses a pool of worker threads fed by a task queue.
ExecutorService pool = Executors.newFixedThreadPool(8);
Future<Integer> f = pool.submit(() -> compute()); // Callable returns a value
Integer result = f.get(2, TimeUnit.SECONDS); // blocks; throws TimeoutException
List<Future<String>> all = pool.invokeAll(tasks); // run many, wait for all
pool.shutdown(); // stop accepting, finish queued tasks
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) pool.shutdownNow(); // interrupt stragglers
// Java 19+: ExecutorService is AutoCloseable
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) { ... }Sizing: CPU-bound work ≈ number of cores. I/O-bound work ≈ cores × (1 + wait time / compute time) — or use virtual threads.
CompletableFuture: composing async work
CompletableFuture<User> userF = CompletableFuture.supplyAsync(() -> userService.load(id), ioPool);
CompletableFuture<List<Order>> ordersF = CompletableFuture.supplyAsync(() -> orderService.forUser(id), ioPool);
CompletableFuture<Dashboard> dash = userF
.thenCombine(ordersF, Dashboard::new) // run both in parallel, combine
.thenApply(Dashboard::withRecommendations) // transform
.orTimeout(2, TimeUnit.SECONDS)
.exceptionally(ex -> Dashboard.fallback()); // recover
CompletableFuture.allOf(f1, f2, f3).join(); // wait for all
CompletableFuture.anyOf(primary, replica).join(); // first to complete| Method | Like |
|---|---|
thenApply | map |
thenCompose | flatMap (the function returns another future) |
thenCombine | Zip two futures |
thenAccept / thenRun | Consume / side effect |
exceptionally / handle / whenComplete | Error handling |
Always pass your own executor for blocking work — the default (ForkJoinPool.commonPool()) is shared and sized for CPU work.
Atomics and adders
Lock-free updates using CPU compare-and-swap (CAS):
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
counter.updateAndGet(x -> Math.max(x, observed));
counter.compareAndSet(expected, newValue);
LongAdder hits = new LongAdder(); // far faster than AtomicLong under heavy contention:
hits.increment(); // spreads updates across cells, sums on read
long total = hits.sum();
AtomicReference<Config> config = new AtomicReference<>(initial);
config.set(reloaded); // safe publication of an immutable objectSynchronizers
| Tool | Purpose | Example |
|---|---|---|
CountDownLatch | Wait until N events happen (one-shot) | Main thread waits for 5 services to start |
CyclicBarrier | N threads wait for each other, repeatedly | Phased simulations |
Semaphore | Limit concurrent access to N permits | At most 10 concurrent calls to an API |
Phaser | Flexible, dynamic barrier | Multi-phase tasks with changing parties |
Exchanger | Two threads swap objects | Pipelined buffers |
Semaphore permits = new Semaphore(10);
permits.acquire();
try { callRateLimitedApi(); } finally { permits.release(); }
CountDownLatch ready = new CountDownLatch(3);
for (var s : services) pool.submit(() -> { s.start(); ready.countDown(); });
ready.await(30, TimeUnit.SECONDS);Concurrent collections
ConcurrentHashMap (with atomic compute, merge, computeIfAbsent), CopyOnWriteArrayList, BlockingQueue implementations (ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue), ConcurrentSkipListMap. See Collections.
Interruption
Java threads are stopped cooperatively. thread.interrupt() sets a flag; blocking methods (sleep, wait, take, join) throw InterruptedException. Long-running loops should check Thread.currentThread().isInterrupted(). Never swallow InterruptedException — rethrow it or restore the flag with Thread.currentThread().interrupt().
Common bugs
| Bug | Cause | Fix |
|---|---|---|
| Race condition | Unsynchronised read-modify-write | Locks, atomics, confinement, immutability |
| Deadlock | Two threads take two locks in opposite order | Global lock order, tryLock with timeout (Deadlocks) |
| Visibility bug | One thread never sees another's write | volatile, locks, atomics (JMM) |
| Thread starvation / pool deadlock | Tasks in a pool block waiting for other tasks in the same full pool | Separate pools; don't block in pool threads |
| Lost exceptions | Exception in submit()ed task sits unseen in the Future | Call get(), or handle inside the task |
| ThreadLocal leaks | Values persist in pooled threads | remove() in finally |
- Use executors, not raw threads; bound queues and pool sizes in production.
- synchronized and locks give mutual exclusion plus visibility; always unlock in finally.
- CompletableFuture composes async tasks: thenApply, thenCompose, thenCombine, exceptionally.
- Atomics and LongAdder for lock-free counters; ConcurrentHashMap's compute methods for atomic updates.
- Latches, semaphores and barriers coordinate threads; interruption is cooperative.
QHow would you make a counter thread-safe? Compare the options.medium
synchronized methods (simple, correct, but contended threads block), AtomicInteger (lock-free CAS, good under moderate contention), LongAdder (striped cells, best under heavy write contention, slightly costlier reads), or confining the counter to one thread. volatile alone is not enough because count++ is a read-modify-write.
QWhat is the difference between submit() and execute()?easy
execute(Runnable) runs a task with no result; an uncaught exception goes to the thread's uncaught exception handler. submit() accepts Runnable or Callable and returns a Future; exceptions are captured in the Future and only surface when you call get(), so they're easily lost if nobody checks.