uopsfof

Untitled

May 29th, 2017
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. package containers;
  2.  
  3. //: containers/References.java
  4. // Demonstrates Reference objects
  5. import java.lang.ref.*;
  6. import java.util.*;
  7.  
  8. class VeryBig {
  9.   private static final int SIZE = 10000;
  10.   private long[] la = new long[SIZE];
  11.   private String ident;
  12.   public VeryBig(String id) { ident = id; }
  13.   public String toString() { return ident; }
  14.   protected void finalize() {
  15.     System.out.println("Finalizing " + ident);
  16.   }
  17. }
  18.  
  19. public class References {
  20.   private static ReferenceQueue<VeryBig> rq =
  21.     new ReferenceQueue<VeryBig>();
  22.   public static void checkQueue() {
  23.     Reference<? extends VeryBig> inq = rq.poll();
  24.     if(inq != null)
  25.       System.out.println("In queue: " + inq.get());
  26.   }
  27.   public static void main(String[] args) {
  28.     int size = 10;
  29.     // Or, choose size via the command line:
  30.     if(args.length > 0)
  31.       size = new Integer(args[0]);
  32.     LinkedList<SoftReference<VeryBig>> sa =
  33.       new LinkedList<SoftReference<VeryBig>>();
  34.     for(int i = 0; i < size; i++) {
  35.       sa.add(new SoftReference<VeryBig>(
  36.         new VeryBig("Soft " + i), rq));
  37.       System.out.println("Just created: " + sa.getLast());
  38.       checkQueue();
  39.     }
  40.     LinkedList<WeakReference<VeryBig>> wa =
  41.       new LinkedList<WeakReference<VeryBig>>();
  42.     for(int i = 0; i < size; i++) {
  43.       wa.add(new WeakReference<VeryBig>(
  44.         new VeryBig("Weak " + i), rq));
  45.       System.out.println("Just created: " + wa.getLast());
  46.       checkQueue();
  47.     }
  48.     SoftReference<VeryBig> s =
  49.       new SoftReference<VeryBig>(new VeryBig("Soft"));
  50.     WeakReference<VeryBig> w =
  51.       new WeakReference<VeryBig>(new VeryBig("Weak"));
  52.     System.gc();
  53.     LinkedList<PhantomReference<VeryBig>> pa =
  54.       new LinkedList<PhantomReference<VeryBig>>();
  55.     for(int i = 0; i < size; i++) {
  56.       pa.add(new PhantomReference<VeryBig>(
  57.         new VeryBig("Phantom " + i), rq));
  58.       System.out.println("Just created: " + pa.getLast());
  59.       checkQueue();
  60.     }
  61.   }
  62. } /* (Execute to see output) *///:~
Advertisement
Add Comment
Please, Sign In to add comment