With a Java ExecutorService, how do I complete actively executing tasks but halt the processing of w

如何让正在执行的任务执行完,等待执行的任务全部取消?

I want something in between these two options.

I want to call a command that:
  a. Completes the currently active task or tasks (like shutdown).
  b. Halts the processing of waiting tasks (like shutdownNow).

I ran into this issue recently. There may be a more elegant approach, but my solution is to first call  shutdown(), then pull out the  BlockingQueue being used by the  ThreadPoolExecutor and call  clear() on it (or else drain it to another  Collection for storage). Finally, calling awaitTermination() allows the thread pool to finish what's currently on its plate.

For example:

public static void shutdownPool(boolean awaitTermination) throws InterruptedException {

    //call shutdown to prevent new tasks from being submitted
    executor.shutdown();

    //get a reference to the Queue
    final BlockingQueue<Runnable> blockingQueue = executor.getQueue();

    //clear the Queue
    blockingQueue.clear();
    //or else copy its contents here with a while loop and remove()

    //wait for active tasks to be completed
    if (awaitTermination) {
        executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS);
    }}

This method would be implemented in the directing class wrapping the ThreadPoolExecutor with the reference executor.

It's important to note the following from the ThreadPoolExecutor.getQueue() javadoc:

Access to the task queue is intended primarily for debugging and monitoring. This queue may be in active use. Retrieving the task queue does not prevent queued tasks from executing.


This highlights the fact that additional tasks may be polled from the  BlockingQueue while you drain it. However, all  BlockingQueue implementations are thread-safe according to  that interface's documentation, so this shouldn't cause problems.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值