kotlinify thread pool (#18366)

chore: Kotlinify thread pool
This commit is contained in:
Omar Basem 2024-01-09 14:35:39 +04:00 committed by GitHub
parent fb13c3016d
commit 3ff6013127
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 44 deletions

View File

@ -1,44 +0,0 @@
package im.status.ethereum.module;
import java.util.concurrent.*;
/** Uses an unbounded queue, but allows timeout of core threads
* (modified case 2 in
* https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html ) */
public class StatusThreadPoolExecutor {
private static final int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
private static final int THREADS_TO_CORES_RATIO = 100;
private static final int KEEP_ALIVE_TIME = 1;
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
private final BlockingQueue<Runnable> mQueue;
private final ThreadPoolExecutor mThreadPool;
private StatusThreadPoolExecutor() {
mQueue = new LinkedBlockingQueue<>();
mThreadPool = new ThreadPoolExecutor(
THREADS_TO_CORES_RATIO * NUMBER_OF_CORES,
THREADS_TO_CORES_RATIO * NUMBER_OF_CORES,
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
mQueue);
// Allow pool to drain
mThreadPool.allowCoreThreadTimeOut(true);
}
/** Pugh singleton */
private static class Holder {
private static StatusThreadPoolExecutor instance = new StatusThreadPoolExecutor();
}
public static StatusThreadPoolExecutor getInstance() {
return Holder.instance;
}
public void execute(final Runnable r) {
mThreadPool.execute(r);
}
}

View File

@ -0,0 +1,47 @@
package im.status.ethereum.module
import java.util.concurrent.*
/**
* Uses an unbounded queue but allows timeout of core threads
* (modified case 2 in
* https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html )
*/
class StatusThreadPoolExecutor private constructor() {
private val NUMBER_OF_CORES: Int = Runtime.getRuntime().availableProcessors()
private val THREADS_TO_CORES_RATIO: Int = 100
private val KEEP_ALIVE_TIME: Int = 1
private val KEEP_ALIVE_TIME_UNIT: TimeUnit = TimeUnit.SECONDS
private val mQueue: BlockingQueue<Runnable> = LinkedBlockingQueue()
private val mThreadPool: ThreadPoolExecutor
init {
mThreadPool = ThreadPoolExecutor(
THREADS_TO_CORES_RATIO * NUMBER_OF_CORES,
THREADS_TO_CORES_RATIO * NUMBER_OF_CORES,
KEEP_ALIVE_TIME.toLong(),
KEEP_ALIVE_TIME_UNIT,
mQueue
)
// Allow pool to drain
mThreadPool.allowCoreThreadTimeOut(true)
}
/** Singleton holder */
private object Holder {
val instance = StatusThreadPoolExecutor()
}
companion object {
@JvmStatic
fun getInstance(): StatusThreadPoolExecutor {
return Holder.instance
}
}
fun execute(r: Runnable) {
mThreadPool.execute(r)
}
}