【问题标题】:Will ThreadPoolExecutor:: afterExecute return runnable in case of exception?如果出现异常,ThreadPoolExecutor::afterExecute 会返回 runnable 吗?
【发布时间】:2017-09-17 04:50:33
【问题描述】:

ThreadPoolExecutor 的 Javadoc 定义 (https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#afterExecute(java.lang.Runnable,%20java.lang.Throwable))

protected void afterExecute(Runnable r, Throwable t)

如果发生异常,初始可运行对象是否会传递给函数?

【问题讨论】:

  • “runnable 被返回”是什么意思?
  • @Jesper 改写
  • 是的,Runnable 被传递给afterExecute,以防Runnable 抛出异常; API 文档对此进行了解释。你究竟为什么怀疑它?你也可以自己试试看(创建一个扩展ThreadPoolExecutor的类,重写afterExecute方法,让它执行一个抛出异常的Runnable,并检查你的afterExecute是否按预期调用) .

标签: java threadpool threadpoolexecutor


【解决方案1】:

它被退回。很容易检查 - 考虑基于 doc 的代码:

public class MainApp {

    public static void main(String[] args) {
        testme();
    }

    public static void testme() {
        ThreadPoolExecutor myown = new ExtendedExecutor(2,4,10, TimeUnit.DAYS.SECONDS, new ArrayBlockingQueue<Runnable>(2));

        myown.execute(() -> {
                throw new RuntimeException("Something went wrong");
  //            System.out.println("Hey there");
        }
    );
}


static class ExtendedExecutor extends ThreadPoolExecutor {

    public ExtendedExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    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("We've got error");
            System.out.println(r==null?"null":"not null");
        }
    }
}

【讨论】:

  • 帮我写这个程序的单元测试用例
猜你喜欢
  • 2016-02-18
  • 1970-01-01
  • 2016-05-23
  • 2019-05-15
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 2017-02-14
相关资源
最近更新 更多