去年年底,我正在运行预定的任务来监视Neo4j集群,而我遇到的问题之一是有时监视会退出。
我最终意识到这是因为RuntimeException被抛出到Runnable方法中,而我没有处理它。 以下代码演示了该问题:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class RunnableBlog {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " -> " + System.currentTimeMillis());
throw new RuntimeException("game over");
}
}, 0, 1000, TimeUnit.MILLISECONDS).get();
System.out.println("exit");
executor.shutdown();
}
}
如果运行该代码,我们将看到RuntimeException,但是执行器不会退出,因为线程在没有通知的情况下就死了:
Exception in thread "main" pool-1-thread-1 -> 1391212558074
java.util.concurrent.ExecutionException: java.lang.RuntimeException: game over
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
at java.util.concurrent.FutureTask.get(Futur