newSingleThreadExecutor vs mutexLock

19 views Asked by At

given the code first

val singleDispatcher = concurrentExecutors.newSingleThreadExecutor(...)

fun foo() {
   GlobalScope.launch(singleDispatcher) {
      task1()
      task2()
   }
}

fun foo1() {
   GlobalScope.launch(singleDispatcher) {
      mutexLock.withLock {
         task1()
         task2()
      }
   }
}

suspend fun task1() {...}
suspend fun task2() {...}

I thought newSingleThreadExecutor will do the same thing as mutextLock as they are both running in sequencial, and only one thread can access the sharedState at a time.

However, from my real life example, the method call foo() sometimes will provide inconsistent state while foo1 always give me correct consistent result. Plz help! thanks so much!

0

There are 0 answers