Search code examples
javamultithreadingscheduling

ScheduledExecutorService Exception handling


I use ScheduledExecutorService to execute a method periodically.

p-code:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> handle =
        scheduler.scheduleWithFixedDelay(new Runnable() {
             public void run() { 
                 //Do business logic, may Exception occurs
             }
        }, 1, 10, TimeUnit.SECONDS);

My question:

How to continue the scheduler, if run() throws Exception? Should I try-catch all Exception in method run()? Or any built-in callback method to handle the Exception? Thanks!


Solution

  • You should use the ScheduledFuture object returned by your scheduler.scheduleWithFixedDelay(...) like so :

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> handle =
            scheduler.scheduleWithFixedDelay(new Runnable() {
                 public void run() { 
                     throw new RuntimeException("foo");
                 }
            }, 1, 10, TimeUnit.SECONDS);
    
    // Create and Start an exception handler thread
    // pass the "handle" object to the thread
    // Inside the handler thread do :
    ....
    try {
      handle.get();
    } catch (ExecutionException e) {
      Exception rootException = e.getCause();
    }