import java.io.*;
public class ShutdownHookDemo {
private String dir = ".";
private String filename = "session_tmp.txt";
/**
* 애플리케이션이 시작되면 shutdown을 생성한후 등록한다.
*/
public void start() {
System.out.println("Demo");
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
/**
* 1. 실행의 순서는 먼저 tempoary파일의 생성
* 2. Runtime클래스에 shutdown hook을 등록
* 3. 사용자의 입력을 기다림(무한루프)
*/
public static void main(String[] args) {
ShutdownHookDemo demo = new ShutdownHookDemo();
demo.setup();
demo.start();
try {
while(true){
System.in.read();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* ShutdownHook클래스를 inner클래스로 사용함으로서 ShutdownHookDemo클래스의
* 멤버변수에 대한 참조를 가능하도록 만든다.
*/
private class ShutdownHook extends Thread {
public void run() {
shutdown();
}
}
/**
* Shutdown의 되는 시점에 생성되었던 temporary파일을 삭제한다.
*/
private void shutdown() {
System.out.println("start shutdown progress.. please wait");
// delete the temp file
File file = new File(dir, filename);
if (file.exists()) {
System.out.println("Deleting temporary file.");
file.delete();
}
}
/**
* 프로그램최초 수행시에 임시파일을 생성해낸다.
*/
private void setup(){
// create a temp file
File file = new File(dir, filename);
try {
System.out.println("Creating temporary file");
file.createNewFile();
}
catch (IOException e) {
System.out.println("Failed creating temporary file.");
}
}
}