分享

best practice to cancel a task in Excutor framework use Future

 moonboat 2011-05-17
//可以很好的取消一个task,但是有一个问题,不会得到task完成的结果
//试用于不需要得到取消的任务的结果,事实上,大部分情况下,我们不要从一个取消的任务中得到结果
public class TimedRun {
    private static final ExecutorService taskExec = Executors.newCachedThreadPool();

    public static void timedRun(Runnable r,
                                long timeout, TimeUnit unit)
            throws InterruptedException {
        Future<?> task = taskExec.submit(r);
        try {
            task.get(timeout, unit);
        } catch (TimeoutException e) {
            // task will be cancelled below
            //
        } catch (ExecutionException e) {
            // exception thrown in task; rethrow
            // the deep exception can be found by invoker, it's importent to rethrow exception,we can't bury it.
            throw launderThrowable(e.getCause());
        } finally {
            // Harmless if task already completed
            task.cancel(true); // interrupt if running
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多