私はこれらの行に沿っていくつかの議論を見ましたが、私の質問に対する具体的な答えはありません。私はスレッドが未知の例外のために死んだときにタスクを再開したい。死んでいるスレッドのUncaughtExceptionHandlerセット内からpool.execute(runnable)を呼び出すことは安全ですか?UncaughtExceptionHandler内からタスクを再実行しますか?
理想的には、throwableがRuntimeExceptionの場合は、プールにrunnableを再送信するだけです。
pool = Executors.newFixedThreadPool(monitors.size(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
threadMap.put(thread, (Monitor)r);
thread.setName(((Monitor)r).getClusterName() + "-monitor");
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread th, Throwable t) {
logger.error("Uncaught exception in thread: " + th.getName(), t);
if (t instanceof RuntimeException) {
Monitor m = threadMap.get(th);
if (m != null && m.runCount() < restartMax) {
logger.error("Restarting monitor due to uncaughtException: " + m.getClusterName());
pool.execute(m);
} }
}
});
return thread;
}
});
これを行うには、より良い方法や安全な方法がありますか?
ありがとうございます!
threadMapは、例外を指定してスレッドに対応するMonitor/Runnableを取得できるようにするためのものです。 restartMaxは、永続的なエラーが直ちに発生するスレッドを無期限に再起動しないようにすることです。このメカニズムは、明示的に処理されていない一時的な例外から回復するためのものです。 – batkins