Created
January 15, 2018 12:47
-
-
Save seveniu/8565cfb99fa8dbf5724625048a208313 to your computer and use it in GitHub Desktop.
java BoundedExecutor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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