virsir
virsir

Reputation: 15509

How to reactive a cancelled futuretask in thread pool?

I use ThreadPoolExecutor to run some actions, at some time I cancelled some future tasks and stored it into a list to arrange some other tasks to do, and after that I want to reactive the saved cancelled future tasks.

But the problem is when I submit the task into the pool, it would not be executed, looks like the cancelled or done flag is saved and recognized by the thread executor, and thus that thread would not be called.

What should I do?

Upvotes: 3

Views: 804

Answers (3)

Tim Bender
Tim Bender

Reputation: 20442

The FutureTask implementation maintains the canceled state. Essentially, when the run() method is called again, it does a CAS operation which fails since the state is not runnable and returns immediately without invoking the inner Callable's call() method. I couldn't see a way to retrieve the original Callable out of it or restore the FutureTask to a non-canceled state.

In response to what should you do... Do you have to cancel them? Why not let them run? If you want priority execution, could you try creating your ThreadPoolexecutor with a PriorityBlockingQueue and use a Comparator to establish the priority. This will allow tasks to be executed in the proper order since they will be added to the PriorityBlockingQueue based on the results of the Comparator.

Upvotes: 3

punkers
punkers

Reputation: 107

If you want to have a return value you can use a Callable. http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

Upvotes: 1

jutky
jutky

Reputation: 3965

Use Runnable instead of threads. The execution pool can handle a Runnable the same way a Thread, but a Runnable could be rerunned number of times.

Upvotes: 1

Related Questions