Enabling runFinalizersOnExit
is unsafe as it might result in erratic behavior and deadlocks on application exit.
Indeed, finalizers might be force-called on live objects while other threads are concurrently manipulating them.
Instead, if you want to execute something when the virtual machine begins its shutdown sequence, you should attach a shutdown hook.
Noncompliant code example
public static void main(String [] args) {
System.runFinalizersOnExit(true); // Noncompliant
}
protected void finalize(){
doShutdownOperations();
}
Compliant solution
public static void main(String [] args) {
Thread myThread = new Thread( () -> { doShutdownOperations(); });
Runtime.getRuntime().addShutdownHook(myThread);
}