ewernli
ewernli

Reputation: 38615

ThreadPoolExecutor: changing corePoolSize at run time

I have a ThreadPoolExecutor with corePoolSize=1 and maxPoolSize=1, backed with an unbounded LinkedBlockingQueue.

Let us say that at time t, the single thread in the pool is processing task T0. There is one task T1 in the queue.

What will happen when I set corePoolSize=0 during the processing of task T0?

In the context of thread pool executors, what does it mean exactly for a thread to be "idle"?

Upvotes: 1

Views: 475

Answers (2)

Maas
Maas

Reputation: 1357

According to the following snippet from :java.util.concurrent.ThreadPoolExecutor.

The pool will become empty when we call setMaximumPoolSize(..)

public void setMaximumPoolSize(int maximumPoolSize) {
        if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
            throw new IllegalArgumentException();
        this.maximumPoolSize = maximumPoolSize;
      -->>  if (workerCountOf(ctl.get()) > maximumPoolSize)
            interruptIdleWorkers();
    }

but when we again try to execute T1 using execute(..) method, the comment stated may give hint of what happens next.

/*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */

My answer is still debatable :)

Upvotes: 0

Tarun
Tarun

Reputation: 182

Single thread will process task T1 also. After that it may be destroyed after being idle for some time.

There are many scenarios for thread to be in idle. It is explained to the point in the below SO post: When is a Java thread idle?

Upvotes: 1

Related Questions