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
FutureTask
wrapping theCallable
by creating it manually and enqueuing viaexecute
. Otherwise,submit
will wrap yourCallable
into anExecutorService
-specific object and put it into the queue, making it impossible to query properties of theCallable
via standard APIs.Using the custom
FutureTask
enqueuing 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 aThreadPoolExecutor
only, you may customize its creation ofFutureTask
instance (starting with Java 6), instead of relying on the submitter doing it:Then, using an instance of
MyThreadPoolExecutor
instead ofThreadPoolExecutor
every submission of anIFormatter
instance will automatically wrapped usingMyFutureTask
instead of the standardFutureTask
. The drawback is that this works only with this specificExecutorService
and the generic method generates an unchecked warning for the special treatment.