package com.mogo.v2x.executor

import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.max
import kotlin.math.min


internal object Executors {

    private val group: ThreadGroup by lazy {
        ThreadGroup("v2x-group")
    }

    private val CPU_CORE_COUNT by lazy {
        Runtime.getRuntime().availableProcessors()
    }

    private val DEFAULT_CORE_COUNT by lazy {
        (max(2, min(CPU_CORE_COUNT - 1, 6)) * 3) + 1
    }

    private const val DEFAULT_MAX_COUNT_4_IO = 128

    val IO by lazy {
        val idGenerator = AtomicLong(0)
        ThreadPoolExecutor(
            DEFAULT_CORE_COUNT, DEFAULT_MAX_COUNT_4_IO, 30, TimeUnit.SECONDS,  LinkedBlockingDeque()
        ) { r ->
            Thread(group, r).apply {
                name = "io-thread-${idGenerator.getAndIncrement()}"
            }
        }
    }
}