kotlingarbage-collectionkotlin-coroutines

How can I tie a coroutine's lifetime to the lifetime of an object?


I have some code similar to this:

class Foo {
    var x = 0
    
    init {
         GlobalScope.launch {
             while (true) {
                 delay(1000)
                 x += 1
             }
         }
    }
}

How can I ensure that the coroutine will be cancelled when its owning instance of Foo is garbage collected?


Solution

  • You can't, certainly not with the code as architected. You must in general manage the lifetimes of coroutines -- and their scopes, strictly avoiding the use of GlobalScope -- more explicitly, e.g. making your Foo a Closeable and managing an explicit CoroutineScope associated with it that gets cancelled when the Foo is closed.

    Even given the limited ways to take action on the garbage collection of a given object or reference, the structure you've specified permanently retains a reference to Foo for the lifetime of the coroutine, so it can never be garbage collected.