I\'m implementing a cache for Objects stored persistently. The idea is:
getObjectFromPersistence(long id); ///Takes about 3 seconds
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) }
}