Java Reference ยท Concurrency
Concurrency in Java: an overview
Overview of Java concurrency: threads, shared state, visibility and atomicity, synchronization, executors, concurrent collections, virtual threads and where to read next.
Concurrency means making progress on several tasks during the same period of time; parallelism means executing them at the same instant on several CPU cores. Java supports both with threads, a memory model that defines what one thread can see of another's writes, and a library (java.util.concurrent) that covers most needs without hand-written thread management.
Concurrent programs are hard for three reasons. Operations that look single-step, such as count++, are really read-modify-write sequences. Threads may see stale values because of CPU caches and compiler reordering. And the order in which threads run is not under your control, so a bug may appear once in a million runs. The tools on this page exist to deal with those three problems.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Key concepts
| Concept | Meaning |
|---|---|
| Thread | An independent path of execution with its own stack. Platform threads map to OS threads; virtual threads (Java 21) are cheap, JVM-managed. |
| Race condition | Result depends on timing between threads accessing shared state. |
| Atomicity | An operation that cannot be observed half-done. count++ is not atomic; AtomicInteger.incrementAndGet() is. |
| Visibility | Whether one thread sees another's writes. Guaranteed by volatile, locks, join, and other happens-before edges. |
| Mutual exclusion | Only one thread at a time runs a critical section (synchronized, Lock). |
| Deadlock | Threads wait for each other forever. Avoid by acquiring locks in a fixed order. |
| Starvation / livelock | A thread never gets to run, or threads keep reacting to each other without progress. |
| Immutability | Data that never changes needs no synchronization. |
| Thread confinement | Keep data in one thread (local variables, ThreadLocal). |
Tools at a glance
| Need | Use |
|---|---|
| Run work in the background | Thread, ExecutorService, virtual threads |
| Get a result later | Future, CompletableFuture |
| Guard shared state | synchronized, ReentrantLock, ReadWriteLock, StampedLock |
| Counters and flags | AtomicInteger, AtomicLong, AtomicReference, LongAdder |
| Shared collections | ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue |
| Coordinate threads | CountDownLatch, CyclicBarrier, Semaphore, Phaser, Exchanger |
| Divide and conquer | ForkJoinPool, parallel streams |
Usage notes
- Start with the simplest safe design: immutable data, confined state, then concurrent collections, then locks. Hand-rolled
wait/notifyis almost never the best choice today. - Prefer executors over
new Threadfor anything beyond a demo; they manage reuse, queuing and shutdown. - Never print results that depend on thread order. Collect results and sort, or join before reading.
- Always shut pools down. A non-daemon pool thread keeps the JVM alive.
try-with-resources on anExecutorServiceworks since Java 19. - Handle
InterruptedException: restore the flag withThread.currentThread().interrupt()if you cannot propagate it. - Parallel streams use the common ForkJoin pool; they pay off for large CPU-bound data, not for I/O or small lists.
- CPU-bound vs I/O-bound: size platform thread pools to the CPU count for the first, and use virtual threads for large numbers of blocking tasks.
- Test concurrency carefully: a passing test proves little. Use stress loops, tools and reviews.