How to guarantee FIFO execution order in a ThreadPoolExecutor

南笙酒味 提交于 2019-12-09 04:48:17

问题


I create a ThreadPoolExecutor with this line of code :

private ExecutorService executor = new ThreadPoolExecutor(5, 10, 120, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20, true));

Then, I run 25 tasks (T01 to T25) so the situation is :

  • 5 tasks currently running (T01 to T05)
  • 20 tasks waiting in the Queue (T06 to T25)

When I put 1 more task (T26), as the queue is full, I expected that the older task (T06) is removed to be launched (because MaxPoolSize is not reached) and the new task (T26) is placed at the end of the queue.

But in real life, if Queue is full and MaxPoolSize is not reached, the newest task is started.

So, I have ...

  • 6 tasks currently running (T01 to T05 and T26)
  • 20 tasks waiting in the Queue (T06 to T25)

... instead of ...

  • 6 tasks currently running (T01 to T06)
  • 20 tasks waiting in the Queue (T07 to T26)

Can I configure the ThreadPoolExecutor to get the expected result ? Should I use another classes ?

For information, part of ThreadPoolExecutor source code

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
        if (runState == RUNNING && workQueue.offer(command)) {
            if (runState != RUNNING || poolSize == 0)
                ensureQueuedTaskHandled(command);
        }
        else if (!addIfUnderMaximumPoolSize(command))
            reject(command); // is shutdown or saturated
    }
}


private boolean addIfUnderMaximumPoolSize(Runnable firstTask) {
    Thread t = null;
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        if (poolSize < maximumPoolSize && runState == RUNNING)
            t = addThread(firstTask);
    } finally {
        mainLock.unlock();
    }
    if (t == null)
        return false;
    t.start();
    return true;
}

Thanks


回答1:


I would make the core size equal the maximum. This is how most of the pools are used and I am not sure when would be the downside in your case, but you would get the tasks executed in order.



来源:https://stackoverflow.com/questions/4431128/how-to-guarantee-fifo-execution-order-in-a-threadpoolexecutor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!