mirror of
https://github.com/mamoe/mirai.git
synced 2025-03-06 17:10:48 +08:00
EventListeners: use atomic lock to avoid redundant object creation
This commit is contained in:
parent
8ea7027fc9
commit
2e614f65f9
@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
package net.mamoe.mirai.event.internal
|
package net.mamoe.mirai.event.internal
|
||||||
|
|
||||||
|
import kotlinx.atomicfu.atomic
|
||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import net.mamoe.mirai.event.Event
|
import net.mamoe.mirai.event.Event
|
||||||
import net.mamoe.mirai.event.EventDisabled
|
import net.mamoe.mirai.event.EventDisabled
|
||||||
@ -87,14 +88,22 @@ internal object EventListenerManager {
|
|||||||
|
|
||||||
private val registries = LockFreeLinkedList<Registry<*>>()
|
private val registries = LockFreeLinkedList<Registry<*>>()
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
private val lock = atomic(false)
|
||||||
internal fun <E : Event> get(clazz: KClass<out E>): EventListeners<E> {
|
|
||||||
return registries.filteringGetOrAdd({ it.clazz == clazz }) {
|
@Suppress("UNCHECKED_CAST", "BooleanLiteralArgument")
|
||||||
Registry(
|
internal tailrec fun <E : Event> get(clazz: KClass<out E>): EventListeners<E> {
|
||||||
clazz,
|
registries.forEach {
|
||||||
EventListeners()
|
if (it.clazz == clazz) {
|
||||||
)
|
return it.listeners as EventListeners<E>
|
||||||
}.listeners as EventListeners<E>
|
}
|
||||||
|
}
|
||||||
|
if (lock.compareAndSet(false, true)) {
|
||||||
|
val registry = Registry(clazz, EventListeners())
|
||||||
|
registries.addLast(registry)
|
||||||
|
lock.value = false
|
||||||
|
return registry.listeners as EventListeners<E>
|
||||||
|
}
|
||||||
|
return get(clazz)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user