com.fireflysource.common.pool.AsyncPool.kt Maven / Gradle / Ivy
package com.fireflysource.common.pool
import com.fireflysource.common.`object`.Assert
import com.fireflysource.common.coroutine.eventAsync
import com.fireflysource.common.func.Callback
import kotlinx.coroutines.future.asCompletableFuture
/**
* @author Pengtao Qiu
*/
interface AsyncPool : Pool {
suspend fun takePooledObject(): PooledObject
suspend fun putPooledObject(pooledObject: PooledObject)
}
class AsyncPoolBuilder {
var maxSize: Int = 16
var timeout: Long = 30
var leakDetectorInterval: Long = 60
var releaseTimeout: Long = 60
private lateinit var objectFactory: Pool.ObjectFactory
private lateinit var validator: Pool.Validator
private lateinit var dispose: Pool.Dispose
private lateinit var noLeakCallback: Callback
fun objectFactory(createPooledObject: suspend (pool: AsyncPool) -> PooledObject) {
objectFactory = Pool.ObjectFactory { pool ->
require(pool is AsyncPool)
eventAsync { createPooledObject.invoke(pool) }.asCompletableFuture()
}
}
fun validator(isValid: (pooledObject: PooledObject) -> Boolean) {
validator = Pool.Validator { isValid.invoke(it) }
}
fun dispose(destroy: (pooledObject: PooledObject) -> Unit) {
dispose = Pool.Dispose { destroy.invoke(it) }
}
fun noLeakCallback(call: () -> Unit) {
noLeakCallback = Callback { call.invoke() }
}
fun build(): AsyncPool {
Assert.isTrue(maxSize > 0, "The max size must be greater than 0")
Assert.isTrue(timeout > 0, "The timeout must be greater than 0")
Assert.isTrue(leakDetectorInterval > 0, "The leak detector interval must be greater than 0")
Assert.isTrue(releaseTimeout > 0, "The release timeout must be greater than 0")
return AsyncBoundObjectPool(
maxSize,
timeout,
objectFactory,
validator,
dispose,
leakDetectorInterval,
releaseTimeout,
noLeakCallback
)
}
}
fun asyncPool(init: AsyncPoolBuilder.() -> Unit): AsyncPool {
val pool = AsyncPoolBuilder()
pool.init()
return pool.build()
}