2013/10/16

java ShutdownHook

java.exeは以下のタイミングで終了する。
    CTRL_C_EVENT
        MS-DOS上で、ctrl+C
    CTRL_CLOSE_EVENT
        MS-DOSの×ボタン
    CTRL_LOGOFF_EVENT
        ユーザがログオフ
    CTRL_SHUTDOWN_EVENT
        PCをシャットダウン
       
       
       
終了することはException処理で対応できない。。
try {
    System.out.println("Start");
    // もろもろの処理
    System.out.println("End");
} catch (Exception e) {
    System.out.println("Exception");
} finally {
    System.out.println("finally");
}

=>Start




解決策としては、shutdownhookを実装する
 // ShutdownHookの設定
 Thread shutdown = new Thread() {
     public void run() {
         System.out.println("Call ShutdownHook");
         // 終了処理
     }
 };
 Runtime.getRuntime().addShutdownHook(shutdown);

 try {
     System.out.println("Start");
     // もろもろの処理
     System.out.println("End");
 } catch (Exception e) {
     System.out.println("Exception");
 } finally {
     System.out.println("finally");
 }

 // ShutdownHookの削除
 Runtime.getRuntime().removeShutdownHook(shutdown);