Last active
November 22, 2018 10:10
-
-
Save ok3141/134ac9ec3c675a88a97a8d8568512a7e to your computer and use it in GitHub Desktop.
Scaling ThreadPoolExecutor. Android. Java
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
| @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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/a/24493856/1891118