I'm using ThreadPoolTaskExecutor for executing my tasks which are implemantations of Callable interface. I just want to check in time if task is still in pool (monitoring). How to do that? I know that I can get queue from ThreadPoolExecutor but how can I cast Runnable to Callable?
Basically I have this callable
public interface IFormatter extends Callable<Integer>{
Long getOrderId();
}
I'm executing it like this
ThreadPoolExecutor.submit(new Formatter(order));
And finally I'd like to loop through queue of ExecutorService in some async method and check if thread with orderId is still there.
As explained in this answer, you may get control over the
FutureTaskwrapping theCallableby creating it manually and enqueuing viaexecute. Otherwise,submitwill wrap yourCallableinto anExecutorService-specific object and put it into the queue, making it impossible to query properties of theCallablevia standard APIs.Using the custom
FutureTaskenqueuing it via
threadPoolExecutor.execute(new MyFutureTask(new Formatter(order)));,you can query order IDs on the queue:
This works for any
ExecutorService(assuming it has a queue). If you are using aThreadPoolExecutoronly, you may customize its creation ofFutureTaskinstance (starting with Java 6), instead of relying on the submitter doing it:Then, using an instance of
MyThreadPoolExecutorinstead ofThreadPoolExecutorevery submission of anIFormatterinstance will automatically wrapped usingMyFutureTaskinstead of the standardFutureTask. The drawback is that this works only with this specificExecutorServiceand the generic method generates an unchecked warning for the special treatment.