
io.p8e.util.IterableExtensions.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of p8e-common Show documentation
Show all versions of p8e-common Show documentation
A collection of services and libraries that iteract and run Provenance Java based contracts.
The newest version!
package io.p8e.util
import org.slf4j.LoggerFactory
import java.time.Duration
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
private val Iterable.sizeOrDefault get() = if (this is Collection<*>) size else 10
private val defaultParmapTimeout = Duration.ofSeconds(10)
private val defaultMinThreadCount = 4
private val cpuBufferCount = 2
private val defaultThreadCount = Runtime.getRuntime().availableProcessors().let { cpus ->
if (cpus < (defaultMinThreadCount + cpuBufferCount)) defaultMinThreadCount else cpus - cpuBufferCount
}.also {
LoggerFactory.getLogger("defaultThreadPooler").info("defaultThreadCount:$it")
}
private val SHARED_FIXED_SIZE_THREAD_POOL: ExecutorService = ThreadPoolFactory.newFixedThreadPool(defaultThreadCount, "default-parmap-%d")
private fun List.copy(): List = ArrayList(this)
private fun Map.copy(): Map = HashMap(this)
fun Iterable.parmapProv(exec: ExecutorService = SHARED_FIXED_SIZE_THREAD_POOL, transform: (T) -> R): List =
Collections.synchronizedList(ArrayList(sizeOrDefault)).also { dest ->
exec.invokeAll(this
.map { Callable { dest += transform(it) } })
.map { it.get() }
}.copy()
fun Map.parmapProv(exec: ExecutorService = SHARED_FIXED_SIZE_THREAD_POOL, transform: (K, V) -> R): Map =
Collections.synchronizedMap(HashMap()).also { dest ->
exec.invokeAll(this
.map { Callable { dest += it.key to transform(it.key, it.value) } })
.map { it.get(defaultParmapTimeout.toMillis(), TimeUnit.MILLISECONDS) }
}.copy()
© 2015 - 2025 Weber Informatics LLC | Privacy Policy