【发布时间】:2016-12-27 10:25:41
【问题描述】:
我创建了一个读取文本文件并使用CompletableFuture 包装调用的小示例。
public class Async {
public static void main(String[] args) throws Exception {
CompletableFuture<String> result = ReadFileUsingLambda(Paths.get("path/to/file"));
result.whenComplete((ok, ex) -> {
if (ex == null) {
System.out.println(ok);
} else {
ex.printStackTrace();
}
});
}
public static CompletableFuture<String> ReadFileUsingSupplier(Path file) throws Exception {
return CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
return new String(Files.readAllBytes(file));
} catch (IOException e) {
e.printStackTrace();
return "test";
}
}
}, ForkJoinPool.commonPool());
}
public static CompletableFuture<String> ReadFileUsingLambda(Path file) throws Exception {
return CompletableFuture.supplyAsync(() -> {
try {
return new String(Files.readAllBytes(file));
} catch (IOException e) {
e.printStackTrace();
return "test";
}
} , ForkJoinPool.commonPool());
}
}
此代码不返回任何内容。它执行并且“没有任何反应”,没有错误或输出。如果我调用ReadFileUsingSupplier 而不是ReadFileUsingLambda,那么我会在控制台中打印文件内容!
对我来说这没有任何意义,因为 lambda 是编写内联函数的简写,它不应该改变行为,但在这个例子中它显然改变了。
【问题讨论】:
标签: java lambda java-8 completable-future