方法一
通常,非常快,并且效果很好。
public static int loops = 500;
private static ExecutorService customPool = Executors.newFixedThreadPool(loops);
.
.
Instant start = Instant.now();
LongSummaryStatistics stats = LongStream.range(0, loops).boxed()
.map(number -> CompletableFuture.supplyAsync(() -> DummyProcess.slowNetworkCall(number), customPool))
.collect(Collectors.toList()).stream() // collect first, else will be sequential
.map(CompletableFuture::join)
.mapToLong(Long::longValue)
.summaryStatistics();
log.info("cf completed in :: {}, summaryStats :: {} ", Duration.between(start, Instant.now()).toMillis(), stats);
// ... cf completed in :: 1054, summaryStats :: LongSummaryStatistics{count=500, sum=504008, min=1000, average=1008.016000, max=1017}
Run Code Online (Sandbox Code Playgroud)
我明白如果我不先收集流,那么由于懒惰的性质,流会一个一个地弹出CompletableFutures,并同步运行。所以,作为一个实验:
方法二
删除中间收集步骤,但也要使流平行!:
Instant start = Instant.now();
LongSummaryStatistics stats …Run Code Online (Sandbox Code Playgroud) 给定一些任意的上下文(例如 Junit 单元测试,而不是特定的,不一定是“主”线程)。
像这样的代码必须引入至少 2 个线程吗?
public static void main (String[] args)
{
CompletableFuture<Void> s = new CompletableFuture<>();
CompletableFuture<Void> f = new CompletableFuture<>();
CompletableFuture<Void> someContext = CompletableFuture.supplyAsync(() ->
{
try{
System.out.println(Thread.currentThread().getId());
CompletableFuture<String> update =
CompletableFuture.supplyAsync(
() -> {
String ans = null;
try {
System.out.println(Thread.currentThread().getId());
ans = "Hello";
} catch (Exception e) {
ans = e.toString();
} finally {
s.complete(null);
return ans;
}
});
s.get();
System.out.println(s.isDone());
} catch (Exception e) {
System.out.println("Some error");
return null;
}
return null;
});
System.out.println(f.isDone()); …Run Code Online (Sandbox Code Playgroud) 我想返回包含所有键到值的映射的映射,这些值是 API 对这些键的响应。我正在使用CompletableFutureandGuava为此。以下是我的尝试。是否有其他标准方法可以使用 Java 8 和线程 API 实现相同的效果?
地图之中id -> apiResponse(id)。
public static List<String> returnAPIResponse(Integer key) {
return Lists.newArrayList(key.toString() + " Test");
}
public static void main(String[] args) {
List<Integer> keys = Lists.newArrayList(1, 2, 3, 4);
List<CompletableFuture<SimpleEntry<Integer, List<String>>>> futures = keys
.stream()
.map(key -> CompletableFuture.supplyAsync(
() -> new AbstractMap.SimpleEntry<>(key, returnAPIResponse(key))))
.collect(Collectors.toList());
System.out.println(
futures.parallelStream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)