Skip to content

Instantly share code, notes, and snippets.

@saswata-dutta
Forked from jexp/CallerBlocksPolicy.java
Created August 4, 2020 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saswata-dutta/8582fccd6661b08e18006c52e9827dce to your computer and use it in GitHub Desktop.
Save saswata-dutta/8582fccd6661b08e18006c52e9827dce 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