fork download
  1. import java.lang.ref.PhantomReference;
  2. import java.lang.ref.ReferenceQueue;
  3. import java.util.concurrent.TimeUnit;
  4.  
  5. class Ideone {
  6. public static void main(String[] args) throws InterruptedException {
  7. Beta b1 = new Beta();
  8. Beta b2 = new Beta();
  9. Alpha a1 = new Alpha();
  10. Alpha a2 = new Alpha();
  11. a1.b1 = b1;
  12. a1.b2 = b1;
  13. a2.b2 = b2;
  14. PhantomReference<Alpha> a1Phantom =
  15. new PhantomReference<>(a1, new ReferenceQueue<>());
  16. PhantomReference<Alpha> a2Phantom =
  17. new PhantomReference<>(a2, new ReferenceQueue<>());
  18. PhantomReference<Beta> b1Phantom =
  19. new PhantomReference<>(b1, new ReferenceQueue<>());
  20. PhantomReference<Beta> b2Phantom =
  21. new PhantomReference<>(b2, new ReferenceQueue<>());
  22. a1 = null;
  23. b1 = null;
  24. b2 = null;
  25. System.gc();
  26. Thread.sleep(TimeUnit.SECONDS.toMillis(1));
  27. System.out.printf(
  28. "a1 has %sbeen collected%n",
  29. a1Phantom.isEnqueued() ? "" : "not ");
  30. System.out.printf(
  31. "a2 has %sbeen collected%n",
  32. a2Phantom.isEnqueued() ? "" : "not ");
  33. System.out.printf(
  34. "b1 has %sbeen collected%n",
  35. b1Phantom.isEnqueued() ? "" : "not ");
  36. System.out.printf(
  37. "b2 has %sbeen collected%n",
  38. b2Phantom.isEnqueued() ? "" : "not ");
  39. }
  40. }
  41.  
  42. class Beta {
  43. }
  44.  
  45. class Alpha {
  46. static Beta b1;
  47. Beta b2;
  48. }
Success #stdin #stdout 0.12s 51528KB
stdin
Standard input is empty
stdout
a1 has been collected
a2 has not been collected
b1 has not been collected
b2 has not been collected