JDK线程池异常被吞掉的设计思考

大家都知道提交任务到线程池有executesubmit两种方式,如果业务处理出异常了,前者会抛出堆栈信息,后者不会,至于为什么,大家可以去看看源码就知道了。

不过我这里有个疑问,就是Doug Lea大神为什么会设计成一种可以抛异常,一种不抛而是自己吞掉呢?

基于这段代码,我是这样想的

final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.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;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

processWorkerExit(w, completedAbruptly); 这句执行到的前提是:线程池中有线程处理任务出现异常了,为什么? 因为while (task != null || (task = getTask()) != null) 会一直阻塞嘛,它里面的逻辑就是把这个异常线程从woker中移除掉,好,也就是说必须抛了异常才能跑到这里,而execute方式如果异常了就能走到这里。

而submit提交方式是不会抛出异常的,因为它走的是下面这段代码,setException(ex)这句吞掉了异常, 代码在FutureTask中

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        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 {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

自然的也不会走到上面 processWorkerExit(w, completedAbruptly); 也就是这种提交任务方式不会因为异常而从woker中移除线程。

总结:
根据上面的分析,我个人理解为什么这样设计,是因为 submit 即使出现异常也不会从线程池中移除当前线程,而 execute 会移除,就是可以有两种选择,不知道这样理解的对不对,反正思考了就对了,请路过的大佬多指教~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值