Artists vs threads

I am trying to run the following code snippet:

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(); } 

In relation to the foregoing, I have the following questions:

  • Is there a way to catch and respond to exceptions that occur in the stream of executors?
  • Why is the exception from a thread explicitly expressed in the main thread, but both executions using the executor service do not propagate this error? How can this error be detected?

EDIT: They recalled another question:

  • How can I stop a given periodic task that I plan, say, after N repetitions or N minutes?
+4
source share
2 answers

Question 2 is really simple - you are not actually starting a new thread, you are just calling run() , which is executed synchronously in the original thread. You should call start() , after which the exception will not be passed back.

As for exception handling in ScheduledExecutorService - if you call Future.get() , it will throw ExecutionException if the original task throws an exception, throwing the original exception as the reason:

An exception that occurs when you try to get the result of a task that is interrupted by throwing an exception. This exception can be checked using the Throwable.getCause() method.

If you need to answer exceptions without blocking for the future, you can wrap your β€œreal” Runnable in another, which is simply delegated to the original run() method, but with the appropriate try / catch block.

+7
source

You can catch it like this:

  ScheduledFuture<?> schedule = service.schedule(r, 0, TimeUnit.SECONDS); try { Object get = schedule.get(); } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } 

If code running in (Scheduled)ExecutorService throws an exception, it will be returned when called wrapped in an ExecutionException

EDIT:

about the cessation of the planned tasks, it has already been discussed and decided .

+6
source

Source: https://habr.com/ru/post/1438766/


All Articles