Skip to content

Instantly share code, notes, and snippets.

@jexp
Last active August 4, 2020 10:10
Show Gist options
  • Save jexp/b6b97c3e873e33efb13906f95672b1d0 to your computer and use it in GitHub Desktop.
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.
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