How to Stop a Runnable Submitted to ExecutorService in Java

executorservicejava

I've implemented subscription in my Java app. When new subscriber added, the application creates new task (class which implements Runnable to be run in the separate thread) and it is added to the ExecutorService like:

public void Subscribe()
{
    es_.execute(new Subscriber(this, queueName, handler));
}

//...

private ExecutorService es_;

Application may register as many subscribers as you want. Now I want implement something like Unsubscribe so every subscriber has an ability to stop the message flow. Here I need a way to stop one of the tasks running in the ExecutorService. But I don't know how I can do this.

The ExecutorService.shutdown() and its variations are not for me: they terminates all the tasks, I want just terminate one of them. I'm searching for a solution. As simple as possible. Thanks.

Best Answer

You can use ExecutorService#submit instead of execute and use the returned Future object to try and cancel the task using Future#cancel

Example (Assuming Subscriber is a Runnable):

Future<?> future = es_.submit(new Subscriber(this, queueName, handler));
...
future.cancel(true); // true to interrupt if running

Important note from the comments:

If your task doesn't honour interrupts and it has already started, it will run to completion.