来自loom-lab,给出代码
var virtualThreadFactory = Thread.ofVirtual().factory();
try (var executorService = Executors.newThreadPerTaskExecutor(virtualThreadFactory)) {
IntStream.range(0, 15).forEach(item -> {
executorService.submit(() -> {
try {
var milliseconds = item * 1000;
System.out.println(Thread.currentThread() + " sleeping " + milliseconds + " milliseconds");
Thread.sleep(milliseconds);
System.out.println(Thread.currentThread() + " awake");
if (item == 8) throw new RuntimeException("task 8 is acting up");
} catch (InterruptedException e) {
System.out.println("Interrupted task = " + item + ", Thread ID = " + Thread.currentThread());
}
});
});
}
catch (RuntimeException e) {
System.err.println(e.getMessage());
}
我希望代码会catch
打印RuntimeException
消息,但事实并非如此。
是我希望太多,还是有一天会像我希望的那样工作?
为了回应 Stephen C 的惊人回答,我完全可以理解,在进一步探索后,我通过以下方式发现
static String spawn(
ExecutorService executorService,
Callable<String> callable,
Consumer<Future<String>> consumer
) throws Exception {
try {
var result = executorService.submit(callable);
consumer.accept(result);
return result.get(3, TimeUnit.SECONDS);
}
catch (TimeoutException e) {
// The timeout expired...
return callable.call() + " - TimeoutException";
}
catch (ExecutionException e) {
// Why doesn't malcontent get caught here?
return callable.call() + " - ExecutionException";
}
catch (CancellationException e) { // future.cancel(false);
// Exception was thrown
return callable.call() + " - CancellationException";
}
catch (InterruptedException e) { // future.cancel(true);
return callable.call() + "- InterruptedException ";
}
}
和
try (var executorService = Executors.newThreadPerTaskExecutor(threadFactory)) {
Callable<String> malcontent = () -> {
Thread.sleep(Duration.ofSeconds(2));
throw new IllegalStateException("malcontent acting up");
};
System.out.println("\n\nresult = " + spawn(executorService, malcontent, (future) -> {}));
} catch (Exception e) {
e.printStackTrace(); // malcontent gets caught here
}
我希望根据文档malcontent
被卷入其中,但事实并非如此。因此,我很难对自己的期望进行推理。spawn
ExecutionException
我对 Project Loom 的大部分希望是,与函数式反应式编程不同,我可以再次依靠异常来做正确的事情,并对它们进行推理,这样我就可以预测会发生什么,而无需运行实验来验证真正发生的事情.
正如史蒂夫乔布斯(在 NeXT)曾经说过的那样:“它就是有效的”
到目前为止,我在 loom-dev@openjdk.java.net 上的帖子还没有得到回复……这就是我使用 StackOverflow 的原因。我不知道吸引 Project Loom 开发人员的最佳方式。