【发布时间】:2014-12-18 18:00:58
【问题描述】:
在 java 中,我想确定当 TimeoutException 发生时填充未来结果的线程的当前堆栈。似乎 TimeoutException 提供的堆栈跟踪中的顶部条目仅指示调用 future.get() 的位置,而不是后台线程的状态。例如:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(10000);
return "";
}
});
try {
future.get(1, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
在此示例中,我发现顶部条目是 future.get(1, TimeUnit.MILLISECONDS) 条目,而不是 Thread.sleep(10000)。我希望堆栈跟踪指示 Thread.sleep(10000) 因为这是当前正在执行的。有没有一种优雅的方式来做到这一点?
我发现如果存在实际执行问题,那么 ExecutionException.printStackTrace() 会指出问题发生在后台线程的什么位置。
【问题讨论】:
标签: java multithreading executorservice