3

I have a task within a ScheduledExecutor running on a regular interval. If there are particular exceptions which I want to boil up to the main thread, what is a clean way to do this? There doesn't seem to be a way to catch exceptions from a ScheduledFuture, and if I simply attempt to throw a RuntimeException on a scheduled task, that task will cease and never be run again by the ScheduledExecutor.

Currently, I just have a public static member in the main thread that I use to receive events from scheduled tasks but this hardly seems ideal. Any recommended reading for me to look at or any ideas?

Edit: Apologies, allow me to expand on this with an example:

public class TestScheduledFuture {

    public static void main(String[] args) {
        ScheduledExecutorService taskScheduler = Executors.newSingleThreadScheduledExecutor();
        ScheduledFuture<?> scheduledFuture = taskScheduler.scheduleAtFixedRate(new TestScheduledTask(),2,2, TimeUnit.SECONDS);
    }
}

My goal here is to simply throw a RuntimeException() in main() if I ever encounter a RuntimeException within TestScheduledTask().

Right now, I have a public static concurrentQueue in the main class which I add exceptions into from the scheduled threads. Perioidically in main() I simply poll the queue and react to any exceptions in the queue. Is there a better way to do this?

RandomUser
  • 4,140
  • 17
  • 58
  • 94

2 Answers2

4

Passing the exceptions back to another thread via a queue seems a perfectly reasonable thing to do tbh. An alternative is, as insighter says, use Thread.setUncaughtExceptionHandler as otherwise the exception just goes unhandled by the ExecutorService. To use this you need need to supply a ThreadFactory when you create it, something like this

class MyThreadFactory implements ThreadFactory {
    private final ThreadFactory DEFAULT_THREAD_FACTORY = Executors.defaultThreadFactory();

    public Thread newThread(Runnable r) {
        Thread thread = DEFAULT_THREAD_FACTORY.newThread(r);
        thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        return thread;
    }
};


class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    public void uncaughtException(Thread t, Throwable e) {
        // give this a reference to main so it can call some method to pass e and t back 
    }
}
Matt
  • 8,367
  • 4
  • 31
  • 61
0
Thread.setDefaultUncaughtExceptionHandler
Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
yetanothercoder
  • 1,689
  • 4
  • 21
  • 43