Search code examples
androidkotlinfinalizer

Kotlin why is finalizaer never called?


I am new to Kotlin and I can not understand how the finalize() method works. I know Swift and there is a method called deinit, which is being called when an object is destroyed. How can I check if an object has been destroyed in Kotlin.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        printTC()
    }

    fun printTC(){
        var tc:TestClass? = TestClass()
        println(tc?.i)
        tc = null
    }

}

class TestClass{

    var i = 0

    init {
        test()
    }

    protected fun finalize(){
        println("TestClass freed")
    }

    fun test(){
        println("test")
    }
}

Solution

  • Garbage collection is not guaranteed to run immediately when there are no more references to an object, which is probably why you're not seeing the finalize method run yet. You can attempt to force it to run by calling System.gc(), but ultimately it's up to the GC implementation to choose when it runs finalizers, so you just shouldn't rely on them in general.

    Android garbage collection may act differently for many reasons, but at least in a simple JVM command line app, this works as you'd expect:

    fun main() {
        var tc: TestClass? = TestClass() // test
        tc = null
        System.gc() // TestClass freed
    }