BBackend CourseLeroy Labs
0/0
Search the course

Java concurrency, covering threads, the memory model, CompletableFuture & virtual threads

Race conditions, visibility and happens-before, synchronized vs locks vs atomics, concurrent collections, CompletableFuture composition, virtual threads, structured concurrency and pinning.

● expertHostel-Web-AppIR3D (Kontentt)

Why you need this

Every Spring singleton is shared by all request threads. Rate limiters, emitter maps, caches and counters are concurrent data structures, whether you planned it or not.

Hostel-Web-AppRateLimitingFilter: ConcurrentHashMap<String, Deque<Long>>

ConcurrentHashMap makes the map thread-safe, but the ArrayDeque inside is not. Two requests from the same IP mutating the same deque at once would be a race. Hostel handles this correctly: isRateLimited wraps the evict, check and append in synchronized (timestamps), so each per-key deque is guarded by its own lock, and different IPs never contend. The alternatives are compute to mutate atomically per key, or a lock-free atomic token bucket.

Core concepts

  • Race condition. The result depends on timing, e.g. count++ is read-modify-write, so two threads can both read 5 and both write 6.
  • Visibility. Without synchronisation, one thread may never see another’s write (CPU caches, reordering). volatile guarantees visibility, not atomicity.
  • Happens-before. The Java Memory Model rule: an unlock happens-before a later lock of the same monitor; a volatile write happens-before a later read of it; Thread.start and join also establish order.
IR3D (Kontentt)private volatile PublicStatsResponse cached

A volatile reference to an immutable object is a correct, lock-free way to publish a cached value: readers always see a fully built object.

Toolbox

Tool Use
synchronized Simple mutual exclusion
ReentrantLock / ReadWriteLock / StampedLock tryLock, timeouts, many readers
AtomicInteger, AtomicReference, LongAdder Lock-free counters and swaps (LongAdder for high contention)
ConcurrentHashMap.compute/merge Atomic per-key updates
CopyOnWriteArrayList Read-mostly listener lists
BlockingQueue Producer/consumer
Semaphore Limit concurrency to N (e.g. outbound API calls)
CountDownLatch, CyclicBarrier, Phaser Coordination

CompletableFuture: parallel fan-out

var stats    = CompletableFuture.supplyAsync(() -> analytics.stats(id), ioPool);
var bookings = CompletableFuture.supplyAsync(() -> bookingRepo.recent(id), ioPool);
var reviews  = CompletableFuture.supplyAsync(() -> reviewRepo.top(id), ioPool);

Dashboard d = CompletableFuture.allOf(stats, bookings, reviews)
    .thenApply(v -> new Dashboard(stats.join(), bookings.join(), reviews.join()))
    .orTimeout(2, TimeUnit.SECONDS)
    .join();

Three 300 ms calls now take about 300 ms instead of 900 ms. Always pass your own executor; the common pool is shared and small.

Virtual threads (Java 21+)

spring.threads.virtual.enabled: true
  • Each request gets a virtual thread, which is cheap (a few KB). You can have millions of them, and they unmount from the OS carrier thread while blocked on I/O.
  • Blocking code (JDBC, RestClient) stays simple and scales like reactive code for I/O-bound work.
  • Pinning. Before JDK 24, a virtual thread blocked inside synchronized pinned its carrier thread. That’s largely fixed in JDK 24+, which is relevant because you’re on Java 25.
  • They don’t create DB capacity. Hikari’s pool still caps concurrency (pool lesson). Use semaphores to protect downstream services.
  • Avoid heavy ThreadLocal use with millions of threads. Scoped values are the modern alternative.

Structured concurrency (preview → finalising)

try (var scope = StructuredTaskScope.open()) {
    var user   = scope.fork(() -> users.find(id));
    var orders = scope.fork(() -> orders.recent(id));
    scope.join();                              // waits for both; cancels siblings on failure
    return new Profile(user.get(), orders.get());
}

Child tasks can’t outlive their scope, so you get no leaked threads, and cancellation propagates.

Check yourself

1. volatile guarantees…
2. Virtual threads mainly help with…
3. Is ConcurrentHashMap<String, ArrayDeque> fully thread-safe for deque mutations?