Basically, I need a machinery to have the following:
Could anyone suggest best way of achieving this, especially items 3-5. I would really appreciate some code example.
Thanks.
Everything but task states and cancelling is standard for thread pools. Cancellations and status state could be done the following way:
enum TaskState {PENDING, RUNNING};
abstract class MyCallable<V> implements Callable<V>{
protected volatile TaskState state = PENDING;
// to make sure state is always set before running the task
protected abstract V doCall();
final V call(){
state = RUNNING;
return doCall();
}
public TaskState getState() { return state; }
}
...
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<V> future = executor.submit(new MyCallable<V>() {
public V doCall() throws Exception {
//... some work ...
if(Thread.interrupted()){
removeFromMap();
return null;
}
}
});
...
future.cancel(true);
To make task cancellable one needs to check Thread.interrupted()
state during it's execution or some other logical boolean flag. After getting a future for the submitted task, future.cancel(true)
should be called to cancel the task by interrupting it.