Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

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/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top