How to guarantee FIFO execution order in a ThreadP

2019-03-16 06:56发布

问题:

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.