Created
November 9, 2020 22:38
-
-
Save ok3141/6c70670bf955a9f8b42c6c517f4a66ec to your computer and use it in GitHub Desktop.
Optimal ThreadPool
This file contains hidden or 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
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