1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
public class ThreadPoolExecutorBuilder {
private int corePoolSize; private int maximumPoolSize; private long keepAliveTime; private TimeUnit unit; private BlockingQueue<Runnable> workQueue; private RejectedExecutionHandler handler; private ThreadFactory threadFactory; private static AtomicInteger threadId = new AtomicInteger();
public ThreadPoolExecutorBuilder() {
int processors = Runtime.getRuntime().availableProcessors();
this.corePoolSize = processors;
this.maximumPoolSize = 2 * processors;
this.keepAliveTime = 8;
this.unit = TimeUnit.SECONDS;
this.workQueue = new ArrayBlockingQueue<>(200); this.handler = new ThreadPoolExecutor.AbortPolicy();
this.threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "threadPoolWorker-" + threadId.getAndIncrement()); } }; }
public ThreadPoolExecutor build() { return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); }
public ThreadPoolExecutorBuilder setCapacity(int corePoolSize, int maximumPoolSize) { this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; return this; }
public ThreadPoolExecutorBuilder setKeepAliveTime(long keepAliveTime, TimeUnit unit) { this.keepAliveTime = keepAliveTime; this.unit = unit; return this; }
public ThreadPoolExecutorBuilder setWorkQueueAndRejectHandler(BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this.workQueue = workQueue; this.handler = handler; return this; }
public ThreadPoolExecutorBuilder setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; return this; } }
|