1

I need to override execute method of executor where I need to change the behavior that threads more than core pool size will be created only when queue is full.

However in real time applications this behavior is undesirable as it can lead to unending wait of task present in queue.

I have changed the execute method as below:

public void execute(Runnable command)
    {
        System.out.println("ActiveCount : " + getActiveCount() + " PoolSize : " + getPoolSize() 
                    + " QueueSize : " + getQueue().size() +" Idle Threads : " +(getPoolSize()-getActiveCount())); 





int c = ctl.get();
              if (workerCountOf(c) < corePoolSize) {
                  if (addWorker(command, true))
                      return;
                  c = ctl.get();
              }
  else if (isRunning(c) && workQueue.offer(command)) 
  {
      int recheck = ctl.get();

    if (getActiveCount() < workerCountOf(recheck) && isRunning(recheck) && workQueue.offer(command)) {
            return;
        }
    if (addWorker(command, false)) { 
                return;
        }       
    else if (! isRunning(recheck) && remove(command))
        {
              reject(command);
        }
     else if (workerCountOf(recheck) == 0)
        {
              addWorker(null, false);
        }
  }
  else 
  {
      reject(command); // add task to the queue


     }
}

Trying to achieve: CoreThreads -> Non-CoreThreads -> Queue instead of CoreThreads -> Queue -> Non-CoreThreads.

harpun
  • 4,022
  • 1
  • 36
  • 40
  • Isnt it the default behaviour..Once queue is full, then only new threads are created for the thread pool. – Vineet Kasat Oct 10 '13 at 06:29
  • 1
    It sounds like you're using the thread pool incorrectly, then. – Jonathon Reinhart Oct 10 '13 at 06:35
  • I feel in his case, threads need to be utilized to max pool size, and if no new thread can be created, then, queue must be used for waiting for any thread to be free...I know this isn't pool default behavior but in general, this is common requirement. – codingenious Oct 10 '13 at 18:34

1 Answers1

1

I dont understand why you need to change execute method, I think, max pool size should not be preferred over queue, as I can see in you code.

I had same problem and you can follow the link :

click to follow the thread.

I feel this should be you last choice, try something else first.

Community
  • 1
  • 1
codingenious
  • 8,385
  • 12
  • 60
  • 90