Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a Runnable submitted to ExecutorService

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.

like image 862
maverik Avatar asked Dec 18 '12 09:12

maverik


People also ask

How do I cancel a runnable task?

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.

Which method can cancel the future task triggered by submit () of ExecutorService?

You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.

How do you stop a runnable in Java?

You can call cancel() on the returned Future to stop your Runnable task.


1 Answers

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.

like image 153
Aviram Segal Avatar answered Oct 12 '22 02:10

Aviram Segal