All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fireflysource.common.pool.AsyncPool.kt Maven / Gradle / Ivy

There is a newer version: 5.0.2
Show newest version
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()
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy