Skip to content

Instantly share code, notes, and snippets.

@seveniu
Created January 15, 2018 12:47
Show Gist options
  • Save seveniu/8565cfb99fa8dbf5724625048a208313 to your computer and use it in GitHub Desktop.
Save seveniu/8565cfb99fa8dbf5724625048a208313 to your computer and use it in GitHub Desktop.
java BoundedExecutor
package com.lavector.concurrency;
import java.util.concurrent.*;
/**
* @author seveniu
* @date 2017-01-09
* @Description
*/
public class BoundedExecutor {
public static ExecutorService getFixedExecutorService(int queueSize, int threadNum) {
BlockingQueue<Runnable> blockingQueue;
if (threadNum < 1) {
throw new IllegalArgumentException("thread number is illegal : " + threadNum);
}
if (queueSize < 0) {
throw new IllegalArgumentException("queue size is illegal : " + threadNum);
}
if (queueSize == 0) {
blockingQueue = new SynchronousQueue<>();
} else {
blockingQueue = new LinkedBlockingDeque<>();
}
return new ThreadPoolExecutor(threadNum, threadNum,
0L, TimeUnit.MILLISECONDS,
blockingQueue, Executors.defaultThreadFactory(), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (!executor.isShutdown()) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
// should not be interrupted
}
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment