import java.util.* ; public class OutOfHeap1 { @Override protected void finalize() throws Throwable { try { System.out.println("Finalize method called for object: " + this.toString()); Thread.sleep(200) ; } finally { // It is good practice to call super.finalize() super.finalize(); } } public static void main(String[] args) throws Throwable { // Create an object and make it eligible for garbage collection immediately for( int i1=0 ; i1<100 ; i1++ ) new OutOfHeap1(); // Suggest the JVM to run the garbage collector. // This is a *suggestion* only, not a command. System.gc(); System.out.println("main method finished. Finalizer may or may not run before program exit."); // Keep the main thread alive for a moment to give the GC a chance (optional) try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }