Skip to content

Instantly share code, notes, and snippets.

@magnusram05
Created June 30, 2019 09:58
Show Gist options
  • Save magnusram05/cfcbf2df96ad49fa6a9d9a41a187e982 to your computer and use it in GitHub Desktop.
Save magnusram05/cfcbf2df96ad49fa6a9d9a41a187e982 to your computer and use it in GitHub Desktop.
Custom ThreadPoolExecutor
static class CustomThreadPoolExecutor extends ThreadPoolExecutor {
CustomThreadPoolExecutor(int corePoolSize,
int maxPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue blockingQueue) {
super(corePoolSize, maxPoolSize, keepAliveTime, unit, blockingQueue,
SearchThreadFactory.newThreadFactory(),
new CallerRunsPolicy());
}
CustomThreadPoolExecutor() {
this(Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors() * 2,
1, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(20));
System.out.println("No of available processors: " + Runtime.getRuntime().availableProcessors());
}
private final ThreadLocal elapsed_time = new ThreadLocal();
@Override
public void beforeExecute(Thread t, Runnable r) {
elapsed_time.set(System.nanoTime());
}
@Override
public void afterExecute(Runnable r, Throwable t) {
long startTime = (Long) elapsed_time.get();
long elapsedTime = System.nanoTime() - startTime;
logger.info("Completed in {}ms", elapsedTime / Math.pow(10, 6));
}
}
static class SearchThreadFactory implements ThreadFactory {
int count;
@Override
public Thread newThread(Runnable r) {
count++;
return new Thread(r, "SearchThread_" + count);
}
public static ThreadFactory newThreadFactory() {
return new SearchThreadFactory();
}
}
@magnusram05
Copy link
Author

  1. A custom ThreadPoolExecutor is created with twice as many available CPU cores
  2. A custom ThreadFactory is created and passed to the ThreadPoolExecutor to give identifiable names to pool threads

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment