将UncaughtExceptionHandler附加到TimerTask

时间:2009-04-01 15:08:41

标签: java multithreading concurrency

是否可以将UncaughtExceptionHandler附加到TimerTask

(除了致电Thread.setDefaultUncaughtExceptionHandler()

2 个答案:

答案 0 :(得分:2)

您可以编写一个TimerTask代理,从Throwable抓取run

public final class TimerTaskCatcher extends TimerTask {
    private final TimerTask orig;
    private final Thread.UncaughtExceptionHandler handler;
    public TimerTaskCatcher(
        TimerTask orig, 
        Thread.UncaughtExceptionHandler handler
    } {
        if (orig == null || handler == null) {
            throw new NullPointerException();
        }
        this.orig = orig;
        this.handler = handler;
    }
    @Override public boolean cancel() {
        return orig.cancel();
    }
    @Override public void run() {
        try {
            orig.run();
        } catch (Throwable exc) {
            handler.uncaughtException(Thread.currentThread(), exc);
        }
    }
    @Override public long scheduledExecutionTime() {
        return orig.scheduledExecutionTime();
    }
}

顺便说一句:您可能需要考虑使用java.util.concurrent代替Timer

答案 1 :(得分:0)

是的,我想是的。 Thread class中有一个实例方法(setUncaughtExceptionHandler)设置了帖子的UncaughtExceptionHandler

run的{​​{1}}方法中,您可以执行以下操作:

TimerTask