Concurrency
26 — Concurrency
Previous: 25 JVM & Memory · Next: 27 Design Patterns
▶️ pkg7concurrency/concurrency1ThreadBasics.java → concurrency8LocksAndCoordination.java
▶️ Advanced: pkg16advconcurrency/
Core concepts
| Concept | Meaning |
|---|---|
| Process | Isolated program with own memory |
| Thread | Lightweight unit within a process; shares heap |
| Race condition | Outcome depends on timing without synchronization |
| Deadlock | Threads wait on each other forever |
Building blocks
1// Thread2Thread t = Thread.startVirtualThread(() -> task()); // Java 213 4// ExecutorService5ExecutorService pool = Executors.newFixedThreadPool(4);6Future<Integer> f = pool.submit(() -> compute());7 8// CompletableFuture9CompletableFuture.supplyAsync(() -> fetch())10 .thenApply(data -> transform(data))11 .thenAccept(System.out::println);12 13// Synchronization14synchronized (lock) { ... }15ReentrantLock lock = new ReentrantLock();16AtomicInteger counter = new AtomicInteger();Virtual threads (Java 21)
Millions of cheap threads for blocking I/O. Don't pool them like platform threads.
⚠️ Pinning: synchronized inside virtual thread may pin to carrier thread.
Learning order
concurrency1Thread basicsconcurrency2Runnable / Callableconcurrency3ExecutorServiceconcurrency4synchronized / volatileconcurrency5Concurrent collectionsconcurrency6CompletableFutureconcurrency7Virtual threadsconcurrency8Locks
Deep dive → 04 Concurrency
Next → 27 Design Patterns
Source named in this chapter
- concurrency1ThreadBasicspkg7concurrency/concurrency1ThreadBasics.java