Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Executors vs threads

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() {
        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:

  1. Is there any way to catch and respond to exceptions happening on the executor's thread?
  2. 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:

  1. How can i stop a given periodic task that I schedule, let's say after N repeats or N minutes?
like image 424
Bober02 Avatar asked Dec 12 '22 21:12


1 Answers

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.

like image 89
Jon Skeet Avatar answered Dec 29 '22 00:12

Jon Skeet