Java Concurrency
Priority: P1 (HIGH)
Modern concurrent programming emphasizing Virtual Threads (Loom) and safety.
Implementation Guidelines
- Virtual Threads (Java 21): Use for high-throughput I/O.
Executors.newVirtualThreadPerTaskExecutor(). - Structured Concurrency: Use
StructuredTaskScopeto treat related tasks as a single unit (Scope, Fork, Join). - Immutability: Share immutable data between threads to avoid race conditions.
- CompletableFuture: Use for composing asynchronous pipelines (if not using Virtual Threads).
- Atomic Variables: Use
AtomicInteger,LongAdderfor simple counters. - Locks: Prefer
ReentrantLock/ReadWriteLockoversynchronizedblocks for fine-grained control. - Thread Safety: Document
@ThreadSafeor@NotThreadSafe.
Anti-Patterns
new Thread(): Never manually create threads. Use Executors.- Thread Pooling Virtual Threads: Virtual threads are cheap; do not pool them.
- Blocking inside
synchronized: Pins the carrier thread (Loom pitfall). UseReentrantLock. - Shared Mutable State: The root of all concurrency bugs.
Thread.stop/suspend: Deprecated and dangerous.
Code
For full StructuredTaskScope and VirtualThread examples:
references/structured-concurrency.md
// Virtual Threads (Loom)
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var user = scope.fork(() -> api.fetchUser());
scope.join().throwIfFailed();
}
Related Topics
language | best-practices