From fb8538ecbedc7292e33f2a756cc4cea0248057d9 Mon Sep 17 00:00:00 2001 From: Mygod Date: Sun, 22 Aug 2021 02:20:02 -0400 Subject: [PATCH] Fix race conditions for cancellables --- mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt b/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt index 47559b39..95ac2bfb 100644 --- a/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt +++ b/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt @@ -400,6 +400,7 @@ class RootServer { CoroutineScope(Dispatchers.Main.immediate + job) } val callbackWorker = newSingleThreadContext("callbackWorker") + // access to cancellables shall be wrapped in defaultWorker val cancellables = LongSparseArray<() -> Unit>() // thread safety: usage of output should be guarded by callbackWorker @@ -424,7 +425,7 @@ class RootServer { val callback = counter Logger.me.d("Received #$callback: $command") when (command) { - is CancelCommand -> cancellables[command.index]?.invoke() + is CancelCommand -> defaultWorker.launch { cancellables[command.index]?.invoke() } is RootCommandOneWay -> defaultWorker.launch { try { command.execute() @@ -434,8 +435,8 @@ class RootServer { } is RootCommand<*> -> { val commandJob = Job() - cancellables.append(callback) { commandJob.cancel() } defaultWorker.launch(commandJob) { + cancellables.append(callback) { commandJob.cancel() } val result = try { val result = command.execute(); { output.pushResult(callback, result) }