Reputation: 9470
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.
Upvotes: 2
Views: 2002
Reputation: 16526
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.
Upvotes: 1
Reputation: 25028
Everything you need is in the tags. If you use a fixed thread pool ExecutorService, you can limit the number of threads that can execute simultaneously.
If more threads are submitted than can be handled, they are held in a queue.
Calling the submit() method of an ExecutorService will give you a Future object which will let you know whether the task is pending or it has been cancelled, etc
I do have a series of tutorials on ExecutorService: http://codelatte.wordpress.com/2013/11/09/a-simple-newfixedthreadpool-example/
How to use Future object: http://codelatte.wordpress.com/2013/11/08/a-simple-cachedthreadpool-example/
Upvotes: 0