You are currently viewing Please help me explaining this coroutine behavior

Please help me explaining this coroutine behavior

I have this piece of code

import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.junit.jupiter.api.Test class ATest { class S1 { var i = true var x = 0 suspend fun start(){ while(i){ delay(500) x++ } } fun isRunning():Boolean{ return x>3 } fun cancel(){ i=false } } @Test fun aTest(){ val s1 = S1() GlobalScope.launch(Dispatchers.Default) { s1.start() } while(s1.isRunning().not()){ println("Q") // THIS LINE } if(s1.isRunning()){ println("cancel") s1.cancel() }else{ println("abc") } } } 

When I run it, everything is fine. It will println a lot of “Q”, then cancel s1, then print “cancel” to the console.

However, if I comment out the line println(“Q”), it will run forever. So strange.

I have tested this on:

  • kotlin 1.5.31 & coroutine 1.6.0-RC
  • koltin 1.5.31 & coroutine 1.5.2
  • kotlin 1.6.0 & coroutine 1.6.0-RC
  • kotlin 1.6.0 & coroutine 1.5.2

All run on jdk 11

Can anyone help me explain this strange behavior?

Thank you

submitted by /u/gthyr666
[link] [comments]