fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class GCTest
  9. {
  10. public static void main(String[] args)
  11. {
  12. GCTest test;
  13. // Without the null assignment
  14. test = create(0);
  15. test = create(1);
  16. test = null;
  17. System.gc();
  18.  
  19. try {Thread.sleep(10);} catch (Exception e){}
  20. System.out.println();
  21.  
  22. // With the null assignment
  23. test = create(2);
  24. test = null;
  25. test = create(3);
  26. test = null;
  27. System.gc();
  28.  
  29. }
  30.  
  31. private int id;
  32.  
  33. public GCTest(int id)
  34. {
  35. this.id = id;
  36. System.out.println("Created " + id);
  37. }
  38.  
  39. private static GCTest create(int id)
  40. {
  41. System.gc();
  42. try {Thread.sleep(10);} catch (Exception e){}
  43. return new GCTest(id);
  44. }
  45.  
  46. @Override
  47. protected void finalize() throws Throwable
  48. {
  49. super.finalize();
  50. System.out.println("Finalize " + id + " from Thread " + Thread.currentThread().getName());
  51. }
  52.  
  53. }
  54.  
Success #stdin #stdout 0.1s 380160KB
stdin
Standard input is empty
stdout
Created 0
Created 1
Finalize 1 from Thread Finalizer
Finalize 0 from Thread Finalizer

Created 2
Finalize 2 from Thread Finalizer
Created 3
Finalize 3 from Thread Finalizer