美文网首页Java学习笔记Java 杂谈
ExecutorService中对异常的处理

ExecutorService中对异常的处理

作者: 静宜君 | 来源:发表于2017-02-15 18:50 被阅读1393次

这篇文章里我们分析一下Executor/ExecutorService中异常的处理方式,ExecutorService加强了Executor这个接口,并提供了submit方法以加强Executor中的execute方法,也正是因为这两个方法某些细微的差异,造成了对异常处理时两个方法的千差万别。

在面对异常时,有如下几种场景

Situation Way to keep safe
Thread 1.自定义UncaughtExceptionHandler
2.用 try/catch代码块包围
3.自己实现Thread的子类去记录异常日志
ThreadPoolExecutor 1.重写afterExecute()方法来记录异常
2.检查Future
Future/ FutureTask 1.调用get方法以获取内部的执行异常
2.重写 FutureTask.done()方法

综上来看,异常处理无非三种方式,要么用trycatch,要么自定义个handler,要么去弄个子类覆盖某些方法,我们今天就来探索探索这里面的

先用一段非常简单的代码来体会下execute和submit对于异常处理的不同

public static void main(String[] args) throws Exception {
        ExecutorService exe = Executors.newFixedThreadPool(1);
        //exe.execute(new Task());
        exe.submit(new Task());
public static class Task implements Runnable {
        @Override
        public void run() {
            System.out.println(Integer.parseInt("123"));
            System.out.println(Integer.parseInt("XYZ"));//这里会抛RuntimeException
        }
    }
}

启动main方法,输出如下(注意!没有异常!)

submit木有异常!

接着注释掉submit,启用execute,则会抛出异常

输出123后抛出异常

我们再修改下main方法

public static void main(String[] args) throws Exception {
        ExecutorService exe = Executors.newFixedThreadPool(1);
        Future f=exe.submit(new Task());
        f.get();
}

这样修改之后,程序也像execute方法那样抛出了异常,这也是这两者之间的差别,submit方法会把异常也当作是任务的一部分,只有调用get了才能拿得到异常。
为什么submit会“吞下”异常直至调用他的get方法呢,我把代码贴出来,就一目了然了。
我们所调用的submit方法,是在AbstractExecutorService中实现的

public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);//将任务包装一下
        execute(ftask);                            //执行任务
        return ftask;
    }

execute方法是在ThreadPoolExecutor中实现的,整个execute方法其实就是判断线程池的状态然后选择到底是new新线程执行还是加入队列等等,干事的就是这一句addWorker(command, true);
之后就会调用内部类Worker的run方法,


我们具体看下这个方法

final void runWorker(Worker w) {//省略了一些状态判断的代码
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run(); //此处调用FutureTask.run()
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
    }

接着FutureTask.run()

public void run() {//省略了一些状态判断的代码
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);   //这里吞下了异常!!!!
                }
                if (ran)
                    set(result);
            }
        } finally {
             //省略了其他代码
        }
    }

这样,异常就被submit给含在嘴里了,要他吐出来,只能去调用他的get方法

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);   //接着往下看
    }
private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);//异常直到这里才会抛出
    }

而如果是execute方法的话,task.run调用的就是Callable或者Runnable的方法了,所以有异常就直接抛了,没有了那FutureTask那层包装。
花了好大功夫明白了为什么submit直到调用get方法才会抛异常,我们来看下解决方案

把submit吞异常给说清楚了,我这里挑几个stackoverflow上比较热门的,ExecutorService中异常处理错误的实践

  • UncaughtExceptionHandler的错误实践

public class ThreadStudy {
    public static void main(String[] args) {
        final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                synchronized (this) {
                    System.err.println("Uncaught exception in thread '" + t.getName() + "': " + e.getMessage());
                }
            }
        };
        // 自定义线程的newThread方法以加入自己的Handler
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                System.out.println("creating pooled thread");
                final Thread thread = new Thread(r);
               //以为这样可以抓住执行过程的异常
                thread.setUncaughtExceptionHandler(exceptionHandler);
                return thread;
            }
        };
        ExecutorService threadPool
                            = Executors.newFixedThreadPool(1, threadFactory);
        Callable callable = new Callable() {
            @Override
            public Integer call() throws Exception {
                throw new Exception("Error in Callable");
            }
        };
        threadPool.submit(callable);
        threadPool.shutdown();
        System.out.println("-----------Done.---------");
    }
}

大家可以自己试试,输出的就只有最后那行Done。

  • afterExecute的错误实践

public class ThreadStudy2 {
    public static class ExceptionCaughtThreadPool extends ThreadPoolExecutor{
        List<Throwable> exceptions=new LinkedList();
        //构造函数省略
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            if (t!=null){
                exceptions.add(t);
                System.out.println("catch exception in afterExecute");
                return;
            }
            System.out.println("everything is ok");
        }
    }
    public static void main(String[] args){
        ExceptionCaughtThreadPool threadPool=new ExceptionCaughtThreadPool(1,1,100,TimeUnit.SECONDS,new LinkedBlockingQueue<>());
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException();
            }
        });
        System.out.println("--------DONE-----------");
    }
}

大家可以接着试试这段代码,输出的是everything is ok。

jdk文档里给了一个我认为是脱裤子放屁的建议,代码如下

class ExtendedExecutor extends ThreadPoolExecutor {
    // 这可是jdk文档里面给的例子。。
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t == null && r instanceof Future<?>) {
            try {
                Object result = ((Future<?>) r).get();
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt(); // ignore/reset
            }
        }
        if (t != null)
            System.out.println(t);
    }
}}

这代码确实让afterExecute方法可以拿到异常了,但又怎么样呢,既然要靠get方法去拿异常,何必我还要自己实现一个线程池然后去覆盖方法再get,我在外面直接future.get()不就好了,如果哪位读者有另外的看法,愿闻其详,反正我是看不出来jdk给这个例子有什么意义(除了告诉你有这么个方法可以覆盖)。

综上所述,在ExecutorService里面处理异常最主流的还是外部调用Future.get()方法后去catch异常,或是直接在runnable的run方法里,对各类异常处理,不过在run方法中处理异常要留心。

我们先看下trycatch的一个例子

public class MyRunnable implements Runnable {
    private final List<Exception>   exceptions;
    public MyRunnable(final List<Throwable> exceptions) {
        this.exceptions = exceptions;
    }
    @Override
    public void run() {
        try {
            processData();
        } catch (final Exception ex) { //接住了所有的异常
            //处理异常
        }
    }
}

这里的一个很大的问题就是catch接住了所有的异常,包括了InterruptedException,这就比较麻烦了,因为中断是线程交互中非常重要的一个手段,这一下被吞了就麻烦了,所以run方法内trycatch要额外注意抓异常的顺序。

public void run(){
    try{
        processData();
    }catch(InterruptedException interrupted){
        //有可能会对中断异常进行特殊处理
    }catch(final Exception ex){ //接住了所有的异常
        //处理异常
    }
 }

综上所述,Executor中对异常的处理也介绍的差不多了,execute貌似只和submit差一个返回值,但是如我们分析的,对于异常的处理,差异还是很大的,因为水平有限,如有错误,恳请您能指出。

参考资料

相关文章

网友评论

    本文标题:ExecutorService中对异常的处理

    本文链接:https://www.haomeiwen.com/subject/vptqwttx.html