
1.簡介
Phantom reference objects, which are enqueued after the collector
determines that their referents may otherwise be reclaimed. Phantom
references are most often used for scheduling pre-mortem cleanup actions in
a more flexible way than is possible with the Java finalization mechanism.
在引用對象被回收后,虛引用會入隊。虛引用最常用于調度預清理操作,比Java的finalization機制更靈活。
<p> If the garbage collector determines at a certain point in time that the
referent of a phantom reference is <a
href="package-summary.html#reachability">phantom reachable</a>, then at that
time or at some later time it will enqueue the reference.
但引用對象變?yōu)樘摽蛇_后,則虛引用會入隊。
<p> In order to ensure that a reclaimable object remains so, the referent of
a phantom reference may not be retrieved: The <code>get</code> method of a
phantom reference always returns <code>null</code>.
get方法總是返回null
<p> Unlike soft and weak references, phantom references are not
automatically cleared by the garbage collector as they are enqueued. An
object that is reachable via phantom references will remain so until all
such references are cleared or themselves become unreachable.
不同于軟引用和弱引用,因為虛引用會入隊所以gc不會自動清除虛引用。
PhantomReference,即虛引用,虛引用并不會影響對象的生命周期。虛引用的作用為:跟蹤垃圾回收器收集對象這一活動的情況。
2.構造器
public class PhantomReference<T> extends Reference<T> {
/**
* Creates a new phantom reference that refers to the given object and
* is registered with the given queue.
*
* <p> It is possible to create a phantom reference with a <tt>null</tt>
* queue, but such a reference is completely useless: Its <tt>get</tt>
* method will always return null and, since it does not have a queue, it
* will never be enqueued.
*
* @param referent the object the new phantom reference will refer to
* @param q the queue with which the reference is to be registered,
* or <tt>null</tt> if registration is not required
*/
public PhantomReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
}
如果ReferenceQueue為空,那么虛引用將毫無作用,因此PhantomReference必須要和ReferenceQueue聯(lián)合使用。而SoftReference和WeakReference可以選擇和ReferenceQueue聯(lián)合使用也可以不選擇,這使他們的區(qū)別之一。
3.get
public T get() {
return null;
}
4.實例
public class TestPhantomReference {
private static ReferenceQueue<Object> rq = new ReferenceQueue<Object>();
public static void main(String[] args) {
Object obj = new Object();
PhantomReference<Object> pr = new PhantomReference<Object>(obj, rq);
System.out.println(pr.get());
Reference<Object> r = (Reference<Object>) rq.poll();
if (r == null) {
System.out.println("before gc ReferenceQueue is null, pr is " + pr);
}
obj = null;
System.gc();
System.out.println(pr.get());
r = (Reference<Object>) rq.poll();
if (r != null) {
System.out.println("after gc, pr enqueue, pr is " + pr);
}
}
}
結果如下:
null
before gc ReferenceQueue is null, pr is java.lang.ref.PhantomReference@6d6f6e28
null
after gc, pr enqueue, pr is java.lang.ref.PhantomReference@6d6f6e28