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:
EDIT: One further question came to mind:
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 calling start()
, at which point the exception won't be propagated back.
As for handling exceptions in a ScheduledExecutorService
- if you call Future.get()
, it will throw ExecutionException
if the original task threw an exception, exposing the original exception as the cause:
Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the
Throwable.getCause()
method.
If you need to respond to exceptions without blocking for the future to complete, you could wrap your "real" Runnable
in another one which just delegated to the original's run()
method, but with an appropriate try/catch block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With