Java – how to ensure FIFO execution order in ThreadPoolExecutor

I use this line of code to create a ThreadPoolExecutor:

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 currently running tasks (T01 to T05) and 20 tasks waiting in the queue (T06 to T25)

When I add another task (T26), when the queue is full, I expect to delete the old task (T06) to start (because maxpoolsize is not reached) and the new task (T26) will be placed at the end of the queue

However, in real life, if the queue is full and does not reach maxpoolsize, the latest task is started

So I have

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

... instead of

>Currently, there are 6 running tasks (T01 to T06) > 20 tasks waiting in the queue (T07 to T26)

Can I configure ThreadPoolExecutor to achieve the desired results? Should I use other classes?

For more information, see part of the 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;
}

thank you

Solution

I'll make the core size equal to the maximum This is how most pools are used. I'm not sure when there will be shortcomings in your case, but you will perform tasks in order

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>