What's the scope of a CoroutineScope?

Viewed 252

I am currently learning about coroutines. In onCreate of my Application class I did the following:

override fun onCreate() {
    super.onCreate()

    val job = CoroutineScope(IO).launch {
        while(true) {
            Timber.i("hello from coroutine")
            delay(1000)
        }
    }

    job.invokeOnCompletion {
        Timber.i("job.invokeOnCompletion")
    }
}

I would have expected the job to be canceled once onCreate is finished, but instead it runs endlessly:

2020-06-28 16:23:11.436 onCreate$job: hello from coroutine
[..]
2020-06-28 16:23:19.489 onCreate$job: hello from coroutine
2020-06-28 16:23:21.504 onCreate$job: hello from coroutine
2020-06-28 16:23:22.512 onCreate$job: hello from coroutine
2020-06-28 16:23:23.516 onCreate$job: hello from coroutine
[..]
2020-06-28 16:23:45.671 onCreate$job: hello from coroutine
  1. So what is the scope of CoroutineScope? Shouldn't it be canceled as soon as the end of onCreate is reached?
  2. Notice the job output, there's a gap between 16:23:19.489 and 16:23:21.504, missing 16:23:20. Can anyone explain why?
  3. I forced a garbage collection multiple times, still the output continues. Would have expected the jobto be garbage collected as it is a local variable?
1 Answers

A thread can't be garbage collected if it's still running.

The coroutine is still running and it won't be canceled when the onCreate() ends. You can attach a coroutine to a lifecycle of a fragment or activity if you want to be canceled automatically when the fragment is destroyed. But, onCreate() and functions in general don't have a lifecycle. If you want to achieve something similar, you have to have job.cancel() at the end of your function.

So to answer your questions:

  1. No, threads (or coroutines) don't get canceled arbitrarily.
  2. CPU was busy running other tasks for 1 sec. IO threads don't have the same priority as UI for example.
  3. You can't force GC, you can only make a suggestion that this is a good time to collect garbages. You shouldn't try to outsmart the GC. Also, there was nothing to be collected.
Related