Skip to content

Instantly share code, notes, and snippets.

@ok3141
Last active November 22, 2018 10:10
Show Gist options
  • Select an option

  • Save ok3141/134ac9ec3c675a88a97a8d8568512a7e to your computer and use it in GitHub Desktop.

Select an option

Save ok3141/134ac9ec3c675a88a97a8d8568512a7e to your computer and use it in GitHub Desktop.
Scaling ThreadPoolExecutor. Android. Java
@NonNull
@UiThread
public Executor getThreadPool() {
if (threadPool == null) {
final String threadNamePrefix = getClass().getSimpleName();
int corePoolSize = 0;
int maxPoolSize = Math.max(2, Runtime.getRuntime().availableProcessors() * 2 + 1);
long keepAliveTime = 10;
ThreadPoolExecutor tp = new ThreadPoolExecutor(
corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
new LinkedTransferQueue<Runnable>() {
@Override
public boolean offer(Runnable e) {
return tryTransfer(e);
}
},
new ThreadFactory() {
final AtomicInteger counter = new AtomicInteger();
public Thread newThread(@NonNull Runnable runnable) {
return new Thread(runnable, threadNamePrefix + "-" + counter.incrementAndGet());
}
},
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
});
tp.allowCoreThreadTimeOut(true);
threadPool = tp;
}
return threadPool;
}
@ok3141

ok3141 commented Nov 22, 2018

Copy link
Copy Markdown
Author

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