Thread Confinement Via One Executor
Confine mutable state to one single-thread executor: every read and write is a submitted task, so no locks or atomic fields are needed.
Code
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConfinedCounter {
// thread confinement: one owner thread serializes all access to this state
private final List<Integer> events = new ArrayList<>();
private final ExecutorService owner = Executors.newSingleThreadExecutor();
public CompletableFuture<Integer> record(int value) {
// every mutation is submitted to the single owner thread; submission order is execution order
return CompletableFuture.supplyAsync(() -> {
events.add(value);
return events.size();
}, owner);
}
public CompletableFuture<Integer> total() {
return CompletableFuture.supplyAsync(
() -> events.stream().mapToInt(Integer::intValue).sum(), owner);
}
public static void main(String[] args) throws Exception {
ConfinedCounter counter = new ConfinedCounter();
counter.record(3);
counter.record(5);
int sum = counter.total().get(); // reads are submitted too, so what you read is always a serialized state
int size = counter.record(1).get();
System.out.println("sum = " + sum + ", size = " + size);
counter.owner.shutdown();
}
}How it works
The moving parts are the class ConfinedCounter and the functions record and total.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Putting it to use
The entry-point signature is public CompletableFuture<Integer> record(int value)
The demo output is labeled (sum =); each label names the call that printed it.
Treat main as the orchestrator calling record and total in a fixed order.
Core lines
private final ExecutorService owner = Executors.newSingleThreadExecutor();
return CompletableFuture.supplyAsync(() -> {
events.add(value);
return events.size();
}, owner);
return CompletableFuture.supplyAsync(
() -> events.stream().mapToInt(Integer::intValue).sum(), owner);
Interactive Tools for This Topic
FAQ
- What does Thread Confinement Via One Executor print when run?
- Running the file directly is enough — expect labeled output lines such as `sum =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.