diff --git a/src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt b/src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt new file mode 100644 index 00000000..0a460a0b --- /dev/null +++ b/src/main/kotlin/org/koitharu/kotatsu/parsers/util/SoftSuspendLazy.kt @@ -0,0 +1,33 @@ +package org.koitharu.kotatsu.parsers.util + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.lang.ref.SoftReference + +/** + * Like a [SuspendLazy] but with [SoftReference] under the hood + */ +class SoftSuspendLazy( + private val initializer: suspend () -> T, +) { + + private val mutex = Mutex() + private var cachedValue: SoftReference? = null + + suspend fun get(): T { + // fast way + cachedValue?.get()?.let { + return it + } + return mutex.withLock { + cachedValue?.get()?.let { + return it + } + val result = initializer() + cachedValue = SoftReference(result) + result + } + } + + suspend fun tryGet() = runCatchingCancellable { get() } +}