Code Review chat中的讨论从ScheduledExecutorService中确定了以下行为:
计划运行的任务在出现“严重”问题时失败,但没有问题的报告、异常或日志。在其他情况下,应用程序通常会因错误而终止。然而,在ScheduledExecutorService的上下文中,根本没有异常/错误“处理”。
首先,编造一个问题。下面的类有一个静态初始化程序,它保证失败:
public class InitializerFault {
private static final int value = Integer.parseInt("fubar");
@Override
public String toString() {
return "" + value;
}
}以下列方式运行时:
public static void main(String[] args) {
System.out.println(new InitializerFault());
}它产生(这正是我所期望的):
Exception in thread "main" java.lang.ExceptionInInitializerError
at SimpleHandler.main(SimpleHandler.java:5)
Caused by: java.lang.NumberFormatException: For input string: "fubar"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at InitializerFault.<clinit>(InitializerFault.java:4)
... 1 more但是,当以下列方式运行时:
private static final Thread buildThread(Runnable r) {
Thread t = new Thread(r, "TestThread");
t.setDaemon(true);
System.out.println("Built thread " + t);
return t;
}
public static void main(String[] args) throws InterruptedException {
// use a thread factory to create daemon threads ... can be non-daemon as well.
ScheduledExecutorService ses = Executors.newScheduledThreadPool(
2, (r) -> buildThread(r));
ses.scheduleAtFixedRate(
() -> {System.out.println(new InitializerFault());},
500, 1000, TimeUnit.MILLISECONDS);
Thread.sleep(3000);
System.out.println("Exiting");
}它产生的只是:
Built thread Thread[TestThread,5,main]
Exiting没有提到任何错误,没有错误,没有转储,什么都没有。这个ExceptionInInitializerError导致了一个复杂的实际调试过程,这个问题很难隔离。
两个问题:
发布于 2014-12-03 14:12:26
ScheduledExecutorService.scheduleAtFixedRate返回一个ScheduledFuture。如果我们调用ScheduledFuture.get(),线程将阻塞并等待周期性任务完成,这可能发生在任务取消或任务抛出异常时。在后一种情况下,get()将抛出带有包装的原始异常的java.util.concurrent.ExecutionException
https://stackoverflow.com/questions/27273581
复制相似问题