Skip to content

Commit

Permalink
Merge pull request #438 from theTd/resettablelazy-leak
Browse files Browse the repository at this point in the history
[6.1.2] Optimize ResettableLazy: Use weak references to prevent memory leak
  • Loading branch information
Bkm016 authored Aug 11, 2024
2 parents f978188 + 299ca8c commit 74c3507
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 74c3507

Please sign in to comment.