voltage

GCTest

Jul 15th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.lang.ref.PhantomReference;
  2. import java.lang.ref.Reference;
  3. import java.lang.ref.ReferenceQueue;
  4.  
  5. public class GCTest {
  6.     @SuppressWarnings("ClassNamingConvention")
  7.     static class A {
  8.         private String myName;
  9.  
  10.         A(String myName) {
  11.             this.myName = myName;
  12.         }
  13.     }
  14.  
  15.     public static void main(String[] args) throws InterruptedException {
  16.         //noinspection LocalCanBeFinal
  17.         A a1 = new A("a1");
  18.         //noinspection LocalCanBeFinal
  19.         A a2 = new A("a2");
  20.  
  21.         final ReferenceQueue<A> collectedReferenced = new ReferenceQueue<>();
  22.         final PhantomReference<A> phantomA1 = new PhantomReference<>(a1, collectedReferenced);
  23.         final PhantomReference<A> phantomA2 = new PhantomReference<>(a2, collectedReferenced);
  24.  
  25.         System.out.println("a1 -> " + phantomA1);
  26.         System.out.println("a2 -> " + phantomA2);
  27.  
  28.         a1 = a2;
  29.  
  30.         //noinspection CallToSystemGC
  31.         System.gc();
  32.  
  33.         //noinspection InfiniteLoopStatement
  34.         while (true) {
  35.             final Reference<? extends A> elem = collectedReferenced.remove();
  36.             System.out.println("collected: " + elem.toString());
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment