Java – Custom cancellation of futuretask

I have implemented custom cancellation logic, as described in concurrency in practice

Encapsulating nonstandard cancellation in a task with newTaskFor.

This works normally. I can call cancel in the future. The task is cancelled as expected I need to be able to destroy the executor service I am using by calling the "shutdown now" method, but this method only calls interupt in the thread, which means that my custom cancellation logic will never be called Because my task uses non - blocking sockets to interrupt threads, it doesn't work, so I have custom cancellation logic

Is there a simple solution to cancel all ongoing tasks I tried to override the shutdown method on ThreadPoolExecutor, but I didn't have access to the worker list I hope I can cancel all contents by closing the execution program, because it is used to submit tasks in several places. Is there a simple solution?

Solution

As John pointed out, it's best to let your task be interrupted You can then simply rely on ThreadPoolExecutor to interrupt all worker threads for orderly cancellation

If this is not possible, you can add additional logic to the ThreadPoolExecutor to achieve what you want It's a bit involved and may not be good for some people (and may damage performance), but I think it will get the job done I think you basically need to maintain an active task list yourself The key is to override the beforeexecute() and afterexecute() methods:

public class MyExecutor extends ThreadPoolExecutor {
    private final Queue<RunnableFuture> activeTasks = 
            new LinkedBlockingQueue<RunnableFuture>();
    ...

    protected void beforeExecute(Thread t,Runnable r) {
        RunnableFuture task = (RunnableFuture)r;
        activeTasks.add(task);
    }

    protected void afterExecute(Thread t,Runnable r) {
        RunnableFuture task = (RunnableFuture)r;
        activeTasks.remove(task);
    }

    public void cancelAllActiveTasks() {
        for (RunnableFuture f: activeTasks) {
            f.cancel(true); // invokes your custom cancellation logic
        }
    }

You can call it by calling cancelallactivetasks() or overriding shutdownnow() One thing I don't like about this is that the task must be deleted from the queue because it is not a constant time operation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>