HashMap with weak values

前端 未结 7 2338
悲&欢浪女
悲&欢浪女 2021-02-18 14:03

I\'m implementing a cache for Objects stored persistently. The idea is:

  • Method getObjectFromPersistence(long id); ///Takes about 3 seconds
  • M
7条回答
  •  隐瞒了意图╮
    2021-02-18 14:22

    I had the need to store tagged weak objects and figured instead of using WeakHashMap, I could just use WeakHashMap instead.

    This is Kotlin, but should apply to Java equally:

    abstract class InstanceFactory {
        @Volatile
        private var instances: MutableMap = WeakHashMap()
    
        protected fun getOrCreate(tag: String = SINGLETON, creator: () -> T): T =
            findByTag(tag)?.let {
                it
            } ?: synchronized(this) {
                findByTag(tag)?.let {
                    it
                } ?: run {
                    creator().also {
                        instances[it] = tag
                    }
                }
            }
    
        private fun findByTag(tag: String): T? = instances.entries.find { it.value == tag }?.key
    
        companion object {
            const val SINGLETON = "singleton"
        }
    }
    

    This can be used as follows:

    class Thing(private val dependency: Dep) { ... }
    
    class ThingFactory(private val dependency: Dep) : InstanceFactory() {
    
        createInstance(tag: String): Thing = getOrCreate(tag) { Thing(dependency) }
    
    }
    

    Simple singletons can be done like this:

    object ThingFactory {
        getInstance(dependency: Dependency): Thing = getOrCreate { Thing(dependency) }
    }
    

提交回复
热议问题