Skip to content

Instantly share code, notes, and snippets.

@ok3141
Created November 9, 2020 22:38
Show Gist options
  • Save ok3141/6c70670bf955a9f8b42c6c517f4a66ec to your computer and use it in GitHub Desktop.
Save ok3141/6c70670bf955a9f8b42c6c517f4a66ec to your computer and use it in GitHub Desktop.
Optimal ThreadPool
public static ThreadPoolExecutor createThreadPool(
int corePoolSize,
int maxPoolSize,
final String threadNamePrefix,
long keepAliveSeconds
) {
ThreadPoolExecutor result = new ThreadPoolExecutor(
corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS,
new LinkedTransferQueue<Runnable>() {
@Override
public boolean offer(Runnable e) {
return tryTransfer(e);
}
},
new ThreadFactory() {
final AtomicInteger counter = new AtomicInteger();
public Thread newThread(@NonNull Runnable runnable) {
return new Thread(runnable, threadNamePrefix + "-" + counter.incrementAndGet());
}
},
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
});
result.allowCoreThreadTimeOut(true);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment