ThreadPoolExecutor that favors new threads over queuing from Open Source

Viewed 94

I have been working with ThreadPoolExecutor and Spring and it's ThreadPoolTaskExecutor. As of JDK 11 there's no built in ThreadPoolExecutor and queue that favors favors new threads over queuing. As well, I can't find any Open Source project that provides this.

What I want is a ThreadPoolExecutor and Queue that will create new threads as new Runnables are submitted and once max threads is reached to queue.

I don't want to set coreThreads == maxThreads as I have 100 threads. Plus I don't want to have all my core threads to setAllowCoreThreadTimeOut as I want a few ready to respond whan a Runnable is submitted.

Yes I can use SynchronousQueue but this rejects the Runnable when we hit the max threads and doesn't queue. The LinkedTransferQueue kind of works but needs to be modified.

The only solution I have found is:

    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(){
        private static final long serialVersionUID = 1L;
        @Override
        protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
            BlockingQueue<Runnable> queue = new LinkedTransferQueue<Runnable>() {
                private static final long serialVersionUID = 1L;
                @Override
                public boolean offer(Runnable e) {
                    return tryTransfer(e);
                }
            };
            return queue;
        }
    };

    executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //if no threads avaiable then put in the queue
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    });

This works exactly as I want, but seems to be a hack/workaround.

I was wondering if Apache, Google, or anywhere this library exists. I find the solution to be a work around and not "hardened" by the community.

Thanks

0 Answers
Related