Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know if a task submitted to executor threw exception?

If I run a thread in a ExecutorService is there a way to know that this thread did not throw an exception when it started execution?

like image 962
Jim Avatar asked Sep 14 '25 11:09

Jim


1 Answers

As per the JavaDoc, you can submit your runnable the the executor using submit()

    ExecutorService service = Executors.newSingleThreadExecutor();
    Future f = service.submit(new Runnable() {
        @Override
        public void run() {
            throw new RuntimeException("I failed for no reason");
        }
    });
    try {
        f.get();            
    } catch (ExecutionException ee) {
        System.out.println("Execution failed " + ee.getMessage());
    } catch (InterruptedException ie) {
        System.out.println("Execution failed " + ie.getMessage());
    }

This method will only work when your exceptions are unchecked. If you have checked exceptions, rethrow them wrapped in a RuntimeException or use the Callable instead of Runnable interface.

like image 176
RudolphEst Avatar answered Sep 17 '25 03:09

RudolphEst