【发布时间】:2019-07-15 15:25:36
【问题描述】:
我正在涉足期货。可以使用 Runnable 和 Callable 创建 Future。有没有办法决定它是如何创建的?
例如,我有以下代码:
Future<?> future = null;
Future<?> future2 = null;
ExecutorService service = null;
service = Executors.newSingleThreadExecutor();
future = service.submit(() -> {
for (int i = 0; i < 5; ++i) {
System.out.println("Printing record: " + i);
Thread.sleep(5);
}
return "Done";
});
future2 = service.submit(() -> System.out.println("Printing zoo inventory"));
System.out.println("================================================================");
System.out.println(future);
System.out.println(future.get().getClass());
System.out.println(future.get());
System.out.println("================================================================");
System.out.println(future2);
try {
System.out.println(future2.get().getClass());
System.out.println(future2.get());
} catch (ExecutionException e) {
System.out.println("Could not do a get");
}
System.out.println("================================================================");
这导致以:
结尾================================================================
java.util.concurrent.FutureTask@5caf905d[Completed normally]
class java.lang.String
Done
================================================================
java.util.concurrent.FutureTask@1f32e575[Completed normally]
Exception in thread "main" java.lang.NullPointerException
at ZooInfo.main(ZooInfo.java:56)
我可以通过以下方式解决这个问题:
if (future2.get() == null) {
System.out.println("Made with a Runnable");
} else {
System.out.println(future2.get().getClass());
System.out.println(future2.get());
}
这样做的问题是,当 Runnable 仍然需要一些时间时,我正在等待获取。有没有办法在不使用 get() 的情况下确定 Future 是使用 Runnable 还是 Callable 创建的?
【问题讨论】:
-
“问题在于”
Callable也可以返回 null。 -
为什么? Runnable 和 Callable 的行为方式相同。
getClass()onnull由get返回但是是个坏主意。 -
这个问题有实际用途吗?通常,当您编写一个依赖于期货的系统时,您知道您发送了什么并且您
get或不get相应地。你不会随意将你不知道的任务倒入你的执行器服务中。 -
即使使用
get,它们也无法区分,因为您也可以在Callable中返回null。 -
在组织中,您计划您的 API。您不只是从未知来源获得随机任务。你编写的模块必须有一定的意义,定义的输入和定义的输出,特别是当你使用像 Java 这样的严格类型的语言时。您的
Future不会有?作为其类型。无论如何,您的情况归结为在对结果使用任何方法之前必须进行空检查 - 因为当您得到未知结果时,其中一些可能为空。