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 returnedFuture
object to try and cancel the task using Future#cancelExample (Assuming
Subscriber
is aRunnable
):Important note from the comments:
If your task doesn't honour interrupts and it has already started, it will run to completion.