jvmMain.io.mockk.impl.platform.JvmWeakConcurrentMap.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mockk-jvm Show documentation
Show all versions of mockk-jvm Show documentation
Mocking library for Kotlin
package io.mockk.impl.platform
import java.lang.ref.ReferenceQueue
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap
class JvmWeakConcurrentMap : MutableMap {
private val map = ConcurrentHashMap()
private val queue = ReferenceQueue()
override fun get(key: K): V? {
return map[StrongKey(key)]
}
override fun put(key: K, value: V): V? {
expunge()
return if (value != null) {
map.put(WeakKey(key, queue), value)
} else {
null
}
}
override fun remove(key: K): V? {
expunge()
return map.remove(StrongKey(key))
}
private fun expunge() {
var ref = queue.poll()
while (ref != null) {
val value = map.remove(ref)
if (value is Disposable) {
value.dispose()
}
ref = queue.poll()
}
}
private class WeakKey(key: K, queue: ReferenceQueue) : WeakReference(key, queue) {
private val hashCode: Int
init {
hashCode = System.identityHashCode(key)
}
override fun equals(other: Any?): Boolean {
if (other === this) {
return true
} else {
val key = get()
if (key != null) {
if (other is WeakKey<*>) {
return key === other.get()
} else if (other is StrongKey<*>) {
return key === other.get()
}
}
}
return false
}
override fun hashCode(): Int {
return hashCode
}
}
private class StrongKey(private val key: K) {
private val hashCode: Int = System.identityHashCode(key)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
} else {
val key = get()
if (key != null) {
if (other is WeakKey<*>) {
return key === other.get()
} else if (other is StrongKey<*>) {
return key === other.get()
}
}
}
return false
}
override fun hashCode(): Int {
return hashCode
}
fun get(): K? {
return key
}
}
override val size
get() = map.size
override fun isEmpty(): Boolean {
return map.isEmpty()
}
override fun containsKey(key: K): Boolean {
return get(key) != null
}
override fun containsValue(value: V): Boolean {
return map.containsValue(value)
}
override fun putAll(from: Map) {
throw UnsupportedOperationException("putAll")
}
override fun clear() {
map.clear()
}
override val entries: MutableSet>
get() = throw UnsupportedOperationException("entries")
override val keys: MutableSet
get() = throw UnsupportedOperationException("entries")
override val values: MutableCollection
get() = map.values
}