Catching thread exceptions from Java ExecutorService

后端 未结 6 1104
闹比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:36

    My original question asked how to implement "robust" thread exception handling with Java ExecutorService. Thanks to Angelo and Greg for pointers on how exception handling works with ExecutorService.submit() and Future.get(). My revised code fragment is shown below. The key point I learned here is that Future.get() catches all exceptions. If the the thread was interrupted or cancelled, you get the appropriate exception, otherwise, the exception is wrapped and re-thrown as an ExecutionException.

    import java.util.concurrent.Callable;
    import java.util.concurrent.CancellationException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class TestThreadFailure {
    
      public static void main(String[] args) {
        int size = 1;
        ExecutorService exec = Executors.newFixedThreadPool(size);
        ThreadFailTask worker = new ThreadFailTask();
        Future result = exec.submit(worker);
        try {
          Integer value = result.get();
          System.out.println("Result: " + value);
        } catch (ExecutionException ex) {
          System.out.println("Caught failure: " + ex.toString());
          exec.shutdownNow();
          return;
        } catch (InterruptedException iex) {
          System.out.println("Thread interrupted: " + iex.toString());
        } catch (CancellationException cex) {
          System.out.println("Thread cancelled: " + cex.toString());
        }
        exec.shutdownNow();
        throw new RuntimeException("Did not catch failure !!");
      }
    
      public static class ThreadFailTask implements Callable {
        @Override
        public Integer call() {
          int nbuf = 65536;
          double[][] buf = new double[nbuf][nbuf];
          return new Integer((int) buf[0][0]);
        }
      }
    }
    

提交回复
热议问题