Last active
August 4, 2020 10:10
-
-
Save jexp/b6b97c3e873e33efb13906f95672b1d0 to your computer and use it in GitHub Desktop.
CallerBlocksPolicy as alternative to CallerRunsPolicy if the calling thread and the pool threads(tasks) share a similar thread local which would then be messed up.
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 ExecutorService createDefaultPool() { | |
int threads = Runtime.getRuntime().availableProcessors()*2; | |
int queueSize = threads * 25; | |
return new ThreadPoolExecutor(threads / 2, threads, 30L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueSize), | |
new CallerBlocksPolicy()); | |
// new ThreadPoolExecutor.CallerRunsPolicy()); | |
} | |
static class CallerBlocksPolicy implements RejectedExecutionHandler { | |
@Override | |
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { | |
if (!executor.isShutdown()) { | |
LockSupport.parkNanos(100); | |
try { | |
// submit again | |
executor.submit(r).get(); | |
} catch (InterruptedException | ExecutionException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment