Knowledge baseExam Center
ENEnglish
Choose language13

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 concurrency

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.

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