I am trying to run the following piece of code:
public static void main(String[] args){
ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2);
Runnable r = new Runnable() {
@Override
public void run() {
throw new RuntimeException();
}
};
service.execute(r );
ScheduledFuture<?> schedule = service.schedule(r, 0, TimeUnit.SECONDS);
new Thread(r).run();
}
Regarding the above I have the following questions:
- Is there any way to catch and respond to exceptions happening on the executor’s thread?
- Why is the exception from the thread created explicitly propagated to the main thread, but both executions using the executor service does not propagate that error? How can this error ever be discovered?
EDIT: One further question came to mind:
- How can i stop a given periodic task that I schedule, let’s say after N repeats or N minutes?
Question 2 is really easy – you’re not actually starting a new thread, you’re just calling
run(), which runs synchronously in the original thread. You should be callingstart(), at which point the exception won’t be propagated back.As for handling exceptions in a
ScheduledExecutorService– if you callFuture.get(), it will throwExecutionExceptionif the original task threw an exception, exposing the original exception as the cause:If you need to respond to exceptions without blocking for the future to complete, you could wrap your “real”
Runnablein another one which just delegated to the original’srun()method, but with an appropriate try/catch block.