凪瀬 BlogのJavaVM終了時に処理をするには - シャットダウンフック - で紹介されてるシャットダウンフックについて実験してみた。
コメントにfinalizeは後処理にはつかえないぜ!って感じのことも書いてあったのでそれも実験。
コードはミニマムなものを書いたので、超シンプル!
Program.java
package com.kazuki.shutdown;
public class Program {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new ShutdownProcess());
new FinalizeObject();
}
}
class ShutdownProcess extends Thread {
@Override
public void run() {
System.out.println("ShutdownProcess#run called.");
}
}
class FinalizeObject {
public FinalizeObject() {
System.out.println("FinalizeObject#init called");
}
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize called.");
}
}
FinalizeObjectにfinalizeメソッドを書いてるのがポイント。これを実行すると下のような結果になる。
FinalizeObject#init called
ShutdownProcess#run called.
確かにシャットダウンフックのShutdownProcess#runメソッドが呼び出されてる。
ただ、悲しい事にFinalizeObjectのfinalizeは呼ばれてない。
呼び出すには…mainメソッドでrunFinalizersOnExitでtureを設定すれば呼ばれることは呼ばれる。
Program.javaから一部抜粋
public class Program {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new ShutdownProcess());
new FinalizeObject();
Runtime.runFinalizersOnExit(true);
}
}
実行結果は、finalizeが呼ばれてるのがわかる。
FinalizeObject#init called
ShutdownProcess#run called.
finalize called.
でも、このrunFinalizersOnExitメソッドは非推奨!!
色々探して見たけど、確実にfinalizeを呼び出す方法は、わからなかった。
まぁ、普通はfinalizeなんかに頼らないコードを書くから関係ないはず。