/*
 * Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.b2international.snowowl.internal.eventbus;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.primitives.Ints;

/**
 * @since 4.5.1
 */
public class WorkerExecutorServiceFactory implements ExecutorServiceFactory {

	@Override
	public ExecutorService createExecutorService(String description, int maxThreads) {
		final ThreadGroup group = new ThreadGroup(description);

		ThreadFactory threadFactory = new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				final Thread thread = new Thread(group, r);
				thread.setName(description + "-" + thread.getId());
				thread.setDaemon(true);
				return thread;
			}
		};

		return new ThreadPoolExecutor(
			Ints.constrainToRange(Runtime.getRuntime().availableProcessors(), 2, maxThreads), maxThreads, 
			1L, TimeUnit.MINUTES,
			new LinkedBlockingQueue<Runnable>(), 
			threadFactory
		);
	}
}

@@ -756,29 +756,83 @@
 t.Linked
-BlockingQueue
+TransferQueue;%0Aimport java.util.concurrent.RejectedExecutionHandler
 ;%0Aimport
@@ -1257,16 +1257,22 @@
 on);%0A%0A%09%09
+final 
 ThreadFa
@@ -1533,22 +1533,136 @@
 %09%09%7D;%0A%0A%09%09
-return
+final ExecutorScalingQueue%3CRunnable%3E queue = new ExecutorScalingQueue%3CRunnable%3E();%0A%09%09final ThreadPoolExecutor executor =
  new Thr
@@ -1808,69 +1808,2082 @@
 %0A%09%09%09
-new LinkedBlockingQueue%3CRunnable%3E(), %0A%09%09%09threadFactory%0A%09%09);%0A%09%7D
+queue, %0A%09%09%09threadFactory,%0A%09%09%09new ForceQueuePolicy()%0A%09%09);%0A%09%09queue.executor = executor;%0A%09%09return executor;%0A%09%7D%0A%09%0A%09/*Elaticsearch maintained class, copied from EsExecutors*/%0A%09static class ExecutorScalingQueue%3CE%3E extends LinkedTransferQueue%3CE%3E %7B%0A%0A        ThreadPoolExecutor executor;%0A%0A        ExecutorScalingQueue() %7B%0A        %7D%0A%0A        @Override%0A        public boolean offer(E e) %7B%0A            // first try to transfer to a waiting worker thread%0A            if (!tryTransfer(e)) %7B%0A                // check if there might be spare capacity in the thread%0A                // pool executor%0A                int left = executor.getMaximumPoolSize() - executor.getCorePoolSize();%0A                if (left %3E 0) %7B%0A                    // reject queuing the task to force the thread pool%0A                    // executor to add a worker if it can; combined%0A                    // with ForceQueuePolicy, this causes the thread%0A                    // pool to always scale up to max pool size and we%0A                    // only queue when there is no spare capacity%0A                    return false;%0A                %7D else %7B%0A                    return super.offer(e);%0A                %7D%0A            %7D else %7B%0A                return true;%0A            %7D%0A        %7D%0A%0A    %7D%0A%09%0A%09/*Elaticsearch maintained class, copied from EsExecutors*/%0A    /**%0A     * A handler for rejected tasks that adds the specified element to this queue,%0A     * waiting if necessary for space to become available.%0A     */%0A    static class ForceQueuePolicy implements RejectedExecutionHandler %7B%0A%0A        @Override%0A        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) %7B%0A            try %7B%0A                // force queue policy should only be used with a scaling queue%0A                assert executor.getQueue() instanceof ExecutorScalingQueue;%0A                executor.getQueue().put(r);%0A            %7D catch (final InterruptedException e) %7B%0A                // a scaling queue never blocks so a put to it can never be interrupted%0A                throw new AssertionError(e);%0A            %7D%0A        %7D%0A%0A    %7D%0A%09
 %0A%7D%0A

use custom queue implementation and rejection policy...