ExecutorService的未来任务没有真正取消 [英] Future task of ExecutorService not truly cancelling

查看:244
本文介绍了ExecutorService的未来任务没有真正取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将ExecutorService中的Futures推入哈希映射。稍后,我可以在哈希映射中调用Futures上的cancel。尽管结果是真的,我后来在Callable过程中打断点,好像Future cancel()没有效果。我认为这可能是一个两个不同的引用在这里(即使引用ID列出为相同的断点时),但是想知道是否一些专家可以chime in。这里的代码看起来像:

I push my Futures from a ExecutorService into a hash map. Later, I may call cancel on Futures from within the hash map. Although the result is true, I later hit breakpoints within the Callable procedure, as if the Future cancel() had no effect. I think it might be a case of two different references here (even though the reference IDs are listed as the same when breakpointing), but was wondering if some experts could chime in. Here's what the code looks like:

ExecutorService taskExecutor = Executors.newCachedThreadPool();
private static Map <String, Future<Object>> results = new HashMap <String, Future<Object>>();       

Future<Object> future = taskExecutor.submit(new MyProcessor(uid));
results.put(uid, future);

我允许处理继续(它是一个循环,提交任务,因为他们传入)我可以尝试通过调用此方法从外部来源取消:

I allow processing to continue (it's a loop that submits tasks as they are passed in), and later I may attempt to cancel from an outside source by calling this method:

public static synchronized boolean cancelThread(String uid) {
    Future<Object> future = results.get(uid);
    boolean success = false;
    if (future != null) {
        success = (future.isDone() ? true : future.cancel(true));
        if (success)
            results.remove(uid);
    }
    return success;     
}

但我还是遇到一个未取消的路径MyProcessor.call )after future.cancel()被调用 - 也就是说,它并没有真正被取消。

But I still encounter a "non-cancelled" path within MyProcessor.call() after future.cancel() is called - i.e. it's not really being cancelled.

我在哪里出错了?

推荐答案


我后来在Callable过程中打断点,好像未来cancel()没有效果。

I later hit breakpoints within the Callable procedure, as if the Future cancel() had no effect.

这是一个常见问题。 Future.cancel(true)等效于 Thread.interrupt()如果任务已经运行,中断位,并导致任何 sleep() wait() c $ c> InterruptedException 。

This is a FAQ. Future.cancel(true) does the equivalent of Thread.interrupt() if the task is already running which sets the interrupt bit on the thread and causes any sleep(), wait(), and some other methods to throw InterruptedException.

它不会停止线程。您需要在线程循环中主动检查中断标志,或者正确处理 InterruptedException

此处了解详情:


如何使用线程的ID暂停线程?

这篇关于ExecutorService的未来任务没有真正取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆