我必须运行多个外部调用操作,然后以列表的形式获取结果。我决定使用CompletableFutureapi,我准备的代码很恶心:
这个例子:
public class Main {
public static void main(String[] args) {
String prefix = "collection_";
List<CompletableFuture<User>> usersResult = IntStream.range(1, 10)
.boxed()
.map(num -> prefix.concat("" + num))
.map(name -> CompletableFuture.supplyAsync(
() -> callApi(name)))
.collect(Collectors.toList());
try {
CompletableFuture.allOf(usersResult.toArray(new CompletableFuture[usersResult.size()])).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
List<User> users = usersResult //the result I need
.stream()
.map(userCompletableFuture -> {
try {
return userCompletableFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
} …Run Code Online (Sandbox Code Playgroud) 我开始阅读Java Concurrency in Practice,我遇到了以下示例(这是一个反面的例子 - 显示了不好的做法):
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
书中的作者写道:
当ThisEscape发布EventListener时,它也隐式发布封闭的ThisEscape实例,因为内部类实例包含对封闭实例的隐藏引用.
当我考虑使用这样的代码时,我可以这样做:
EventSource eventSource = new EventSource();
ThisEscape thisEscape = new ThisEscape(eventSource);
Run Code Online (Sandbox Code Playgroud)
我可以获得对已注册的EventListener的引用,但是我能获得对封闭的ThisEscape实例的引用是什么意思?
有人能给我一个这样的行为的例子吗?用例是什么?