2007-07-20 03:18:25 +00:00
|
|
|
import java.lang.ref.ReferenceQueue;
|
|
|
|
import java.lang.ref.Reference;
|
|
|
|
import java.lang.ref.WeakReference;
|
|
|
|
import java.lang.ref.PhantomReference;
|
2009-09-01 23:23:30 +00:00
|
|
|
import java.util.WeakHashMap;
|
2007-07-20 03:18:25 +00:00
|
|
|
|
|
|
|
public class References {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Object a = new Object();
|
|
|
|
Object b = new Object();
|
|
|
|
Object c = new Object();
|
|
|
|
Object d = new Object();
|
2009-09-01 23:23:30 +00:00
|
|
|
Object e = new Object();
|
|
|
|
Object f = new Object();
|
2007-07-20 03:18:25 +00:00
|
|
|
|
|
|
|
ReferenceQueue q = new ReferenceQueue();
|
|
|
|
|
|
|
|
Reference ar = new WeakReference(a);
|
|
|
|
Reference br = new WeakReference(b, q);
|
|
|
|
Reference cr = new WeakReference(c, q);
|
|
|
|
Reference dr = new PhantomReference(d, q);
|
2009-09-01 23:23:30 +00:00
|
|
|
Reference er = new MyReference(e, q, "foo");
|
|
|
|
|
|
|
|
WeakHashMap<Key,Object> map = new WeakHashMap();
|
|
|
|
map.put(new Key("foo"), f);
|
2007-07-20 03:18:25 +00:00
|
|
|
|
2009-09-01 23:23:30 +00:00
|
|
|
a = b = c = d = e = cr = null;
|
2007-07-20 03:18:25 +00:00
|
|
|
|
|
|
|
System.out.println("a: " + ar.get());
|
|
|
|
System.out.println("b: " + br.get());
|
|
|
|
System.out.println("d: " + dr.get());
|
2009-09-01 23:23:30 +00:00
|
|
|
System.out.println("e: " + er.get());
|
|
|
|
System.out.println("f: " + map.get(new Key("foo")));
|
2007-07-20 03:18:25 +00:00
|
|
|
|
|
|
|
System.gc();
|
|
|
|
|
|
|
|
System.out.println("a: " + ar.get());
|
|
|
|
System.out.println("b: " + br.get());
|
|
|
|
System.out.println("d: " + dr.get());
|
2009-09-01 23:23:30 +00:00
|
|
|
System.out.println("e: " + er.get());
|
|
|
|
System.out.println("f: " + map.get(new Key("foo")));
|
2007-07-20 03:18:25 +00:00
|
|
|
|
|
|
|
for (Reference r = q.poll(); r != null; r = q.poll()) {
|
|
|
|
System.out.println("polled: " + r.get());
|
|
|
|
}
|
|
|
|
}
|
2009-09-01 23:23:30 +00:00
|
|
|
|
|
|
|
private static class MyReference extends WeakReference {
|
|
|
|
private final Object foo;
|
|
|
|
|
|
|
|
public MyReference(Object target, ReferenceQueue queue, Object foo) {
|
|
|
|
super(target, queue);
|
|
|
|
this.foo = foo;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static class Key {
|
|
|
|
private final String name;
|
|
|
|
|
|
|
|
public Key(String name) {
|
|
|
|
this.name = name;
|
|
|
|
}
|
|
|
|
|
|
|
|
public int hashCode() {
|
|
|
|
return name.hashCode();
|
|
|
|
}
|
|
|
|
|
|
|
|
public boolean equals(Object o) {
|
|
|
|
return o instanceof Key && ((Key) o).name.equals(name);
|
|
|
|
}
|
|
|
|
}
|
2007-07-20 03:18:25 +00:00
|
|
|
}
|