Use Mutex than @Synchronized

This commit is contained in:
Him188 2021-11-18 02:56:17 +00:00
parent 5368e6b809
commit df92607841

View File

@ -10,6 +10,8 @@
package net.mamoe.mirai.internal.network.components package net.mamoe.mirai.internal.network.components
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import net.mamoe.mirai.event.nextEvent import net.mamoe.mirai.event.nextEvent
import net.mamoe.mirai.internal.QQAndroidBot import net.mamoe.mirai.internal.QQAndroidBot
import net.mamoe.mirai.internal.network.component.ComponentKey import net.mamoe.mirai.internal.network.component.ComponentKey
@ -23,7 +25,7 @@ import net.mamoe.mirai.utils.info
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
internal interface MessageSvcSyncer { internal interface MessageSvcSyncer {
fun startSync() suspend fun startSync()
suspend fun joinSync() suspend fun joinSync()
companion object : ComponentKey<MessageSvcSyncer> companion object : ComponentKey<MessageSvcSyncer>
@ -41,12 +43,13 @@ internal class MessageSvcSyncerImpl(
@Volatile @Volatile
private var job: Job? = null private var job: Job? = null
private val lock = Mutex()
private fun initScope() { private fun initScope() {
scope = parentContext.addNameHierarchically("MessageSvcSyncerImpl").childScope() scope = parentContext.addNameHierarchically("MessageSvcSyncerImpl").childScope()
} }
@Synchronized override suspend fun startSync(): Unit = lock.withLock {
override fun startSync() {
scope?.cancel() scope?.cancel()
initScope() initScope()
job = scope!!.launch { syncMessageSvc() } job = scope!!.launch { syncMessageSvc() }
@ -65,8 +68,7 @@ internal class MessageSvcSyncerImpl(
logger.info { "Syncing friend message history: Success." } logger.info { "Syncing friend message history: Success." }
} }
@Synchronized override suspend fun joinSync(): Unit = lock.withLock {
override suspend fun joinSync() {
job?.join() job?.join()
} }
} }