CKTIS / Java
Asynchrony and concurrency in Java
Asynchrony and concurrency in Java: Java 21 concurrency includes Thread, ExecutorService, Future, CompletableFuture, and virtual threads, while the Java Memory Model defines visibility through happens-before relations. The Java Memory Model (JMM) defines cross-thread reads; for ordinary mutable or non-final state, safe publication requires happens-before from completed initialization to the reader.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
async concurrencyJava 21 concurrency includes Thread, ExecutorService, Future, CompletableFuture, and virtual threads, while the Java Memory Model defines visibility through happens-before relations. The Java Memory Model (JMM) defines cross-thread reads; for ordinary mutable or non-final state, safe publication requires happens-before from completed initialization to the reader.
Use Executors.newVirtualThreadPerTaskExecutor for many blocking I/O tasks, and bound CPU-bound parallelism near the available core count. Separately, JLS 17.5 gives initialization-safety/freeze to final fields of a properly constructed holder whose this did not escape; those fields can be seen even through a data-race transfer of the reference.
supplyAsync without an Executor normally uses ForkJoinPool.commonPool, so blocking can starve unrelated work; volatile does not make compound operations atomic. The final-field guarantee does not publish independent non-final/mutable state; that state still needs volatile, locking, a concurrent collection, start/join, or Executor submission.
Future.get establishes visibility of task effects; cancel(true) and interrupt are cooperative, so blocking code or loops must respond correctly to interruption. Double-checked locking requires volatile; Future.get gives happens-before from task actions to its reader, and ExecutorService submission from submitter actions to the task.
supplyAsync supplies 21, thenApply doubles it, and join waits for completion; deterministic stdout 42 demonstrates CompletableFuture stage composition.
Examples
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
int result = CompletableFuture.supplyAsync(() -> 21).thenApply(n -> n * 2).join();
System.out.println(result);
}
}
Result
42
supplyAsync supplies 21, thenApply doubles it, and join waits for completion; deterministic stdout 42 demonstrates CompletableFuture stage composition.
Sources
- JLS 21 §17.4.5 — Happens-before Order
- JLS 21 §17.5 — final Field Semantics
- Java SE 21 — Executors.newVirtualThreadPerTaskExecutor
- Java SE 21 — Future memory-consistency contract
- Java SE 21 — ExecutorService memory-consistency contract
- Java SE 21 — java.util.concurrent package
- Java SE 21 — CompletableFuture