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.
We can cancel a task running on a dedicated Thread by invoking Thread. interrupt. This approach is applicable only if the application owns the thread, if the application is using a thread pool, the ExecutorService implementation not the application owns the threads.
You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.
You can call cancel() on the returned Future to stop your Runnable task.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With