`
zhouchaofei2010
  • 浏览: 1085812 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

源代码分析为什么ThreadPoolExecutor的submit方法不会把运行时异常不会交给UncaughtExceptionHandler处理

阅读更多
源代码分析为什么ThreadPoolExecutor的submit方法不会把运行时异常不会交给UncaughtExceptionHandler处理
版本:jdk1.6
 
submit在父类AbstractExecutorService中,所以分析AbstractExecutorService
AbstractExecutorService
 
 
public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }
 
 
分析    RunnableFuture<T> ftask = newTaskFor(task, result);

 

 
 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
 
 
 
 
 public FutureTask(Runnable runnable, V result) {
        sync = new Sync(Executors.callable(runnable, result));
    }
 
 
Executors.callable(runnable, result)
 
 
 public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }
 
 
 RunnableAdapter<T>(task, result);
 
 public T call() {
            task.run();
            return result;
        } 
 
 
分析结果 :Executors.callable没有对run的运行异常处理
 
 
继续分析  FutureTask.run(),注意callable
 
 sync.innerRun();
 
sync. innerRun
        void innerRun() {
            if (!compareAndSetState(0, RUNNING))
                return;
            try {
                runner = Thread.currentThread();
                if (getState() == RUNNING) // recheck after setting thread
                    innerSet(callable.call());
                else
                    releaseShared(0); // cancel
            } catch (Throwable ex) {
                innerSetException(ex);
            }
        }
 
这里通过Throwable可以捕捉运行时异常,分析 innerSetException(ex);
 
 void innerSetException(Throwable t) {
     for (;;) {
  int s = getState();
  if (s == RAN)
      return;
                if (s == CANCELLED) {
      // aggressively release to set runner to null,
      // in case we are racing with a cancel request
      // that will try to interrupt runner
                    releaseShared(0);
                    return;
                }
  if (compareAndSetState(s, RAN)) {
                    exception = t;
                    result = null;
                    releaseShared(0);
                    done();
      return;
                }
     }
        }
 
这里没有把t再抛出
 
所以用submit提交的任务,万一抛出运行时异常,也被程序处理了,不会抛给jvm了,所以不会交给UncaughtExceptionHandler处理
 
那么,如何处理任务抛出运行时异常后,需要一些资源关闭、异常日志记录等问题呢,只能用重写afterExecute(Runnable r ,Throwable ex) 方法了
 
总结:使用submit提交任务时 ,会把原始任务包裹成FutureTask,FutureTask中的run方法捕捉到了运行时异常处理并没有再抛出

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics