2015-04-20 15:36:01 -07:00
|
|
|
|
//: containers/References.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
// Demonstrates Reference objects
|
|
|
|
|
import java.lang.ref.*;
|
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
|
|
class VeryBig {
|
|
|
|
|
private static final int SIZE = 10000;
|
|
|
|
|
private long[] la = new long[SIZE];
|
|
|
|
|
private String ident;
|
|
|
|
|
public VeryBig(String id) { ident = id; }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public String toString() { return ident; }
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
protected void finalize() {
|
|
|
|
|
System.out.println("Finalizing " + ident);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class References {
|
|
|
|
|
private static ReferenceQueue<VeryBig> rq =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new ReferenceQueue<>();
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public static void checkQueue() {
|
|
|
|
|
Reference<? extends VeryBig> inq = rq.poll();
|
|
|
|
|
if(inq != null)
|
|
|
|
|
System.out.println("In queue: " + inq.get());
|
|
|
|
|
}
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
int size = 10;
|
|
|
|
|
// Or, choose size via the command line:
|
|
|
|
|
if(args.length > 0)
|
|
|
|
|
size = new Integer(args[0]);
|
|
|
|
|
LinkedList<SoftReference<VeryBig>> sa =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new LinkedList<>();
|
2015-04-20 15:36:01 -07:00
|
|
|
|
for(int i = 0; i < size; i++) {
|
2015-05-05 11:20:13 -07:00
|
|
|
|
sa.add(new SoftReference<>(
|
2015-04-20 15:36:01 -07:00
|
|
|
|
new VeryBig("Soft " + i), rq));
|
|
|
|
|
System.out.println("Just created: " + sa.getLast());
|
|
|
|
|
checkQueue();
|
|
|
|
|
}
|
|
|
|
|
LinkedList<WeakReference<VeryBig>> wa =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new LinkedList<>();
|
2015-04-20 15:36:01 -07:00
|
|
|
|
for(int i = 0; i < size; i++) {
|
2015-05-05 11:20:13 -07:00
|
|
|
|
wa.add(new WeakReference<>(
|
2015-04-20 15:36:01 -07:00
|
|
|
|
new VeryBig("Weak " + i), rq));
|
|
|
|
|
System.out.println("Just created: " + wa.getLast());
|
|
|
|
|
checkQueue();
|
|
|
|
|
}
|
|
|
|
|
SoftReference<VeryBig> s =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new SoftReference<>(new VeryBig("Soft"));
|
2015-04-20 15:36:01 -07:00
|
|
|
|
WeakReference<VeryBig> w =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new WeakReference<>(new VeryBig("Weak"));
|
2015-04-20 15:36:01 -07:00
|
|
|
|
System.gc();
|
|
|
|
|
LinkedList<PhantomReference<VeryBig>> pa =
|
2015-05-05 11:20:13 -07:00
|
|
|
|
new LinkedList<>();
|
2015-04-20 15:36:01 -07:00
|
|
|
|
for(int i = 0; i < size; i++) {
|
2015-05-05 11:20:13 -07:00
|
|
|
|
pa.add(new PhantomReference<>(
|
2015-04-20 15:36:01 -07:00
|
|
|
|
new VeryBig("Phantom " + i), rq));
|
|
|
|
|
System.out.println("Just created: " + pa.getLast());
|
|
|
|
|
checkQueue();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} /* (Execute to see output) *///:~
|