Stop Runnable Presented in ExecutorService

I implemented a subscription in my Java application. When adding a new subscriber, the application creates a new task (a class that implements Runnable to run in a separate thread), and is added to the ExecutorService as:

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

An application can register as many subscribers as possible. Now I want to implement something like Unsubscribe so that each subscriber has the opportunity to stop the flow of messages. Here I need a way to stop one of the tasks performed in the ExecutorService . But I do not know how I can do this.

ExecutorService.shutdown() and its variants are not for me: they complete all the tasks, I just want to finish one of them. I am looking for a solution. As simple as possible. Thanks.

+7
source share
2 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 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.

+8
source

Instead of using ExecutorService.execute(Runnable) try using Future<?> submit(Runnable) . This method will send Runnable to the pool for execution and return a Future object. In this case, you will have links to all subscriber streams.

To stop a specific thread, just use futureObj.cancel(true) . This will interrupt the current thread by throwing an InterruptedException . The subscriber stream must be encoded so that it stops processing in the event of this exception (for example, Thread.sleep(millis) with a try / catch block of the shell for the entire method).

You can find more information about the official API: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html http://docs.oracle.com/javase/6/ docs / api / java / util / concurrent / ExecutorService.html

+3
source

All Articles