实现说明
底层就是类 ConfinedCounter和函数 record、total。
stream 管道把“做什么”(变换)与“何时做”(终端 collect)分开。
使用要点
- 跑完文件,输出里会留下标记——
sum =。 main的演示流程是record、total——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「单线程执行器线程封闭」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 sum = 标签标明各步骤。
主签名形如 public CompletableFuture<Integer> record(int value)
核心语句
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);
代码示例
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();
}
}