Lifecycle of constructor parameters in Kotlin

Viewed 74

I am trying to understand the lifecycle of constructor parameters in Kotlin. Given the following code, when will FooFactory class instance be available for collection by garbage collector?

Since the usage of FooFactory is delayed, will the runtime know when to release it?

Or will this create a leak if the compiler does not know when to release FooFactory and it will live forever?


class Foo {
    fun doStuff() {}
}

class FooFactory {
    fun getFoo() : Foo {
        return Foo()
    }
}

class User(factory: FooFactory) {
    val x: Foo by lazy {
        factory.getFoo()
    }
}

val user = User(FooFactory())

Thread.sleep(100)

user.x.doStuff()

Thread.sleep(100)
1 Answers

If you look at the implementation of the lazy delegate, which uses SynchronizedLazyImpl, you'll see that the initializing lambda is set to null as soon as the value has been computed:

val typedValue = initializer!!()
_value = typedValue
initializer = null

So by this line:

user.x.doStuff()

FooFactory is eligible for garbage collection. However if x is never accessed, then FooFactory will only be garbage collected once the containing User object is garbage collected.

Related