Skip to content

Commit

Permalink
[6.1.2] Optimize ResettableLazy: Use weak references to prevent memor…
Browse files Browse the repository at this point in the history
…y leaks
  • Loading branch information
theTd committed Aug 10, 2024
1 parent f978188 commit 299ca8c
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions common-util/src/main/kotlin/taboolib/common/util/LazyMaker.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package taboolib.common.util

import java.util.*
import com.google.common.cache.CacheBuilder

/**
* 声明一个线程不安全的延迟加载对象
Expand All @@ -22,7 +22,7 @@ fun <T> resettableLazy(vararg groups: String, synchronized: Boolean = false, ini
} else {
ResettableLazyImpl(*groups, initializer = initializer)
}.also {
ResettableLazy.defined += it
ResettableLazy.defined.put(it, Unit)
}
}

Expand All @@ -32,17 +32,15 @@ abstract class ResettableLazy<T>(vararg val groups: String) : Lazy<T> {

companion object {

val defined = LinkedList<ResettableLazy<*>>()
val defined = CacheBuilder.newBuilder().weakKeys().build<ResettableLazy<*>, Unit>()

fun reset(vararg groups: String) {
synchronized(defined) {
if (groups.isEmpty() || groups.contains("*")) {
defined.forEach { it.reset() }
} else {
defined.filter { lazy ->
groups.any { lazy.groups.contains(it) }
}.forEach { it.reset() }
}
if (groups.isEmpty() || groups.contains("*")) {
defined.asMap().keys.forEach { it.reset() }
} else {
defined.asMap().keys.filter { lazy ->
groups.any { lazy.groups.contains(it) }
}.forEach { it.reset() }
}
}
}
Expand Down

0 comments on commit 299ca8c

Please sign in to comment.