All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.anthavio.httl.async.ExecutorServiceBuilder Maven / Gradle / Ivy

The newest version!
package net.anthavio.httl.async;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author martin.vanek
 *
 */
public class ExecutorServiceBuilder {

	public static ExecutorServiceBuilder begin() {
		return new ExecutorServiceBuilder();
	}

	private int corePoolSize = 1;
	private int maximumPoolSize = 10;
	private int maximumQueueSize = 0;
	private long keepAliveTime = 60L;
	private TimeUnit timeUnit = TimeUnit.SECONDS;
	private ThreadFactory threadFactory = new NamedDeamonThreadFactory();
	private RejectedExecutionHandler rejectionHandler = new RejectingPolicy();

	public ThreadPoolExecutor build() {
		BlockingQueue queue;
		if (maximumQueueSize == 0) {
			//this is not a queue actually - directly pushing requests to threads
			queue = new SynchronousQueue();
		} else {
			queue = new ArrayBlockingQueue(maximumQueueSize);
		}
		//LinkedBlockingQueue

		return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, queue, threadFactory,
				rejectionHandler);
	}

	public ExecutorServiceBuilder setCorePoolSize(int corePoolSize) {
		this.corePoolSize = corePoolSize;
		return this;
	}

	public ExecutorServiceBuilder setMaximumPoolSize(int maximumPoolSize) {
		this.maximumPoolSize = maximumPoolSize;
		return this;
	}

	public ExecutorServiceBuilder setKeepAliveTime(long keepAliveTime, TimeUnit unit) {
		this.keepAliveTime = keepAliveTime;
		this.timeUnit = unit;
		return this;
	}

	public ExecutorServiceBuilder setThreadFactory(ThreadFactory threadFactory) {
		this.threadFactory = threadFactory;
		return this;
	}

	public ExecutorServiceBuilder setRejectionHandler(RejectedExecutionHandler rejectionHandler) {
		this.rejectionHandler = rejectionHandler;
		return this;
	}

	public ExecutorServiceBuilder setMaximumQueueSize(int maximumQueueSize) {
		this.maximumQueueSize = maximumQueueSize;
		return this;
	}

}

/**
 * Custom handle with nice explaining message
 * 
 * @author martin.vanek
 *
 */
class RejectingPolicy implements RejectedExecutionHandler {

	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		throw new RejectedExecutionException("Cannot start " + r + "  active: " + executor.getActiveCount() + ", pool: "
				+ executor.getPoolSize() + " of " + executor.getMaximumPoolSize() + " , queue: "
				+ executor.getQueue().getClass().getSimpleName() + " " + executor.getQueue().size());

	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy