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

com.neko233.skilltree.commons.objectPool.ObjectPool233.kt Maven / Gradle / Ivy

There is a newer version: 0.3.6
Show newest version
package com.demo.actor.objectPool

import java.util.*
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue

/**
 * 对象池
 *
 * @author luohaojun on 2023-10-01
 */
data class ObjectPool233(
    // 对象池唯一名字
    private val uniqueName: String,
    // 最大缓存数量
    private val maxCount: Int,
    // 如何创建一个新的对象
    private val creator: () -> T,
    // 如何销毁一个对象、将该对象还原
    private val destroyer: (T) -> T,

    ) : ObjectPoolApi {

    // 是否一开始就初始化
    private val isInitFirst: Boolean = true

    // 队列
    private val objPoolQueue: BlockingQueue = ArrayBlockingQueue(maxCount)

    init {
        if (isInitFirst) {
            initPool()
        }
    }

    // 初始化对象池
    private fun initPool() {
        while (objPoolQueue.size < maxCount) {
            val obj = creator.invoke()
            objPoolQueue.offer(obj)
        }
    }

    override fun getUniqueName(): String {
        return uniqueName
    }

    override fun getObjectPoolQueue(): Queue {
        return objPoolQueue
    }

    override fun getMaxCount(): Int {
        return maxCount
    }

    override fun getDestroyer(): (T) -> T {
        return destroyer
    }

    override fun getCreator(): () -> T {
        return creator
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy