异常捕获
以前使用executor的时候,为了记录任务线程的异常退出会使用ThreadFactory来设置线程的UncaughtExceptionHandler,但是按照书上的验证发现,采用executorService.submit执行任务时,线程抛出的异常并不会被该处理器捕获,而当使用executor.execute提交任务时则会被捕获。代码如下:
final UncaughtExceptionHandler handler = new UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { System.out.println("uncaught exception"); } }; ThreadFactory exFactory = new ThreadFactory() { @Override public Thread newThread(final Runnable r) { Thread x = new Thread(r); x.setUncaughtExceptionHandler(handler); return x; } }; ExecutorService es = Executors.newSingleThreadExecutor(exFactory);
// es.execute(new Runnable() { es.submit(new Runnable() { @Override public void run() { ArrayList<Integer> x = new ArrayList<Integer>(); System.out.println(x.get(10)); // index out of bound } });
如果要获得submit任务的异常需要使用其返回的future对象,执行器get方法如下:
ExecutorService es = Executors.newSingleThreadExecutor(exFactory); Future<Void> f = (Future<Void>) es.submit(new Runnable() { @Override public void run() { ArrayList<Integer> x = new ArrayList<Integer>(); System.out.println(x.get(10)); } }); try { f.get(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ExecutionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }
此时程序会打印错误信息。