Tools

预计阅读时间:1分钟

ObjectPool

ObjectPool是通用的无锁并发安全对象池. 它也是泄漏安全的:所有尚未回收但由GC回收的对象不会导致任何与池有关的问题,而只会导致分配损失. 请注意,这并不意味着泄漏的对象根本不会引起任何问题,因为丢失的对象可以容纳一些本机或外部资源. 唯一的保证是,如果丢失了对象, ObjectPool不会ObjectPool .

interface ObjectPool<T : Any> : Closeable {
    val capacity: Int
    fun borrow(): T
    fun recycle(instance: T)
    fun dispose()
    fun close() = dispose()
}

inline fun <T : Any, R> ObjectPool<T>.useBorrowed(block: (T) -> R): R // alias of useInstance
inline fun <T : Any, R> ObjectPool<T>.useInstance(block: (T) -> R): R
val ExampleIntArrayPool = object : DefaultPool<IntArray>(ARRAY_POOL_SIZE) {
    override fun produceInstance(): IntArray = IntArray(ARRAY_SIZE)
}

class ExampleDirectByteBufferPool(val bufferSize: Int, size: Int) : DefaultPool<ByteBuffer>(size) {
    override fun produceInstance(): ByteBuffer = java.nio.ByteBuffer.allocateDirect(bufferSize)

    override fun clearInstance(instance: ByteBuffer): ByteBuffer {
        instance.clear()
        return instance
    }

    override fun validateInstance(instance: ByteBuffer) {
        require(instance.isDirect)
        require(instance.capacity() == bufferSize)
    }
}

by  ICOPY.SITE