Why is this an issue?
Running finalizers on JVM exit is disabled by default. It can be enabled with System.runFinalizersOnExit
and
Runtime.runFinalizersOnExit
, but both methods are deprecated because they are inherently unsafe.
According to the Oracle Javadoc:
It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic
behavior or deadlock.
If you really want to execute something when the virtual machine begins its shutdown sequence, you should attach a shutdown hook.
Noncompliant code example
fun main() {
...
System.runFinalizersOnExit(true) // Noncompliant
...
}
Compliant solution
fun main() {
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
doSomething()
}
})
}
Resources
- CERT, MET12-J. - Do not use finalizers. Although this resource talks about Java, the
underlying information concerning the JVM are just as relevant for Kotlin.