컴퓨터/JAVA

The Finalize Method

Hikasiru 2006. 6. 15. 11:08

객체가 서비스로부터 제거 되었을 때 작동할 행동을 정의 하자.
(번역 하니까 이상하군...)

예제.

public class ShutdownDemo {
  public static void main(String[] args) throws Exception {

  // Create an Object with a finalize() method.
  Object f = new Object() {
       public void finalize() {
           System.out.println("Running finalize()");
       }
  };

  // Add a shutdownHook to the JVM
  Runtime.getRuntime().addShutdownHook(new Thread() {
       public void run() {
           System.out.println("Running Shutdown Hook");
       }
  });

  // Unless the user puts -f (for "free") on the command line,
  // call System.exit while holding a reference to
  // Object f, which can therefore not be finalized( ).
  if (args.length == 1 && args[0].equals("-f")) {
       f = null;
       System.gc();
  }

  System.out.println("calling System.exit()");
  System.exit(0);
  }
}


source: Chapter 9, Object Oriented Technique, Java Cookbook 2nd Edtion.