Search code examples
javamultithreadingexecutorserviceproducer-consumer

executor cancel pending task - help needed


Basically, I need a machinery to have the following:

  1. Fixed-sized thread pool to run tasks
  2. Queue of pending tasks (requested, but not yet running)
  3. Cancelling task in pending queue (task is identified by id)
  4. Cancelling ongoing task
  5. Given task id, query whether task is Pending or Running

Could anyone suggest best way of achieving this, especially items 3-5. I would really appreciate some code example.

Thanks.


Solution

  • 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.