Created
June 30, 2019 09:58
-
-
Save magnusram05/cfcbf2df96ad49fa6a9d9a41a187e982 to your computer and use it in GitHub Desktop.
Custom ThreadPoolExecutor
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
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(); | |
} | |
} |
Author
magnusram05
commented
Jun 30, 2019
- A custom ThreadPoolExecutor is created with twice as many available CPU cores
- 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