Catching thread exceptions from Java ExecutorService

后端 未结 6 1094
闹比i
闹比i 2020-12-30 04:18

I\'m working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 04:47

    To Handling exceptions in ExecutorService you have to take the advantage of Callable and Future.

    Callable is similar to Runnable and both are functional interface but run() of Runnable doesn't throws exception and the return type is void where as call() of Callable returns a generics and throws exception.

    Java-8 way:

    ExecuterService executor = null; 
    Future future = null;
    
    Callable yourTask = () -> {
        //your implementation here();
        //your implementation here();
    };
    
    try 
       {
            executor = Executors.newCachedThreadPool();
            future = executor.submit(yourTask );
            Integer result = future.get();
            System.out.println(result);
       }
       catch (ExecutionException | TimeoutException | InterruptedException e) 
       {
        // TODO: handle exception
       }
       finally 
       {
           executer.shutdown();
       }
    

提交回复
热议问题