001 /** 002 * Exercise 4.11 from the book. 003 * 004 * @author Kristian Torp, torp (at) cs (dot) aau (dot) dk 005 * @version 1.0 006 */ 007 public class Exercise4_11 { 008 009 /** The name */ 010 String name; 011 012 /** 013 * Default constructor. 014 */ 015 public Exercise4_11() { 016 this.name = "John Doe"; 017 System.out.println(name + " is alive"); 018 } 019 020 /** 021 * Constructor that takes a single string argument. 022 * 023 * @param name 024 * the name 025 */ 026 public Exercise4_11(String name) { 027 this.name = name; 028 System.out.println(name + " is alive"); 029 } 030 031 /** 032 * The finalize method. 033 * 034 * @see java.lang.Object#finalize() 035 */ 036 public void finalize() { 037 System.out.println("Bye bye " + name + " is dying"); 038 } 039 040 /** 041 * Main method that creates a lot of objects and call the garbage collector 042 * once in a while 043 */ 044 public static void main(String[] args) { 045 046 // loop a number of times 047 for (int i = 0; i < 200; i++) { 048 // every ten times explicitly call the garbage collector 049 if ((i % 10) == 0) { 050 System.gc(); 051 } 052 053 try { 054 Exercise4_11 c = new Exercise4_11("Elvis " + i); 055 // sleep for 100 millisecond 056 Thread.sleep(100); 057 } catch (InterruptedException e) { 058 System.out.println("Interrupted"); 059 } 060 } 061 } 062 } 063