目录
- 零、前情概要
- ref包内容
- 系列目录
- 上一章回顾
- 一、PhantomReference
- 适用场景
- 优雅和提前规避
- Java中使用native memory
- 常规做法
- 借助于Java引用机制
- 处理流程
- 二、jdk.internal.ref.Cleaner
- 源码注释
- 源码概览
- dummyQueue
- add/remove
- 为什么需要这条双向链表
- create/thunk/clean
- java.nio.DirectByteBuffer
- 为什么不让你使用Cleaner
- 总结
零、前情概 要
1.java.lang.ref包的内容
- Reference & ReferenceQueue & ReferenceHandler
- SoftReference & WeakReference
- PhantomReference
- jdk.internal.ref.Cleaner
- FinalReference
- Finalizer & FinalizerThread
- java.lang.ref.Cleaner
- # 其中会涉及两个虚拟机线程:ReferenceHandler & FinalizerThread
2.系列目录
- 《ref包简述》
- 《Reference & ReferenceQueue & ReferenceHandler》
- 《SoftReference & WeakReference》
- 《PhantomReference & jdk.internal.ref.Cleaner》
- 《FinalReference & Finalizer & FinalizerThread》
- 《当WeakReference的referent重写了finalize方法时会发生什么》
- 《java.lang.ref.Cleaner》
3.上一章回顾
- 弱引用的适用场景和相关案例
- 理解弱可达
- 弱引用的处理流程
- 软引用的适用场景
- 理解软可达
- 虚拟机是如何量化软引用的“内存紧张”
- 软引用的时间戳
- -XX:SoftRefLRUPolicyMSPerMB
- 软引用清除策略ReferencePolicy
- Java引用预处理ReferenceProcessor
- 模型逻辑:正常情况、GC频繁、异常情况
一、PhantomReference
1.使用场景
API documentation:PhantomReference (Java SE 15 & JDK 15) (oracle.com)
Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used to schedule post-mortem cleanup actions.
Suppose the garbage collector determines at a certain point in time that an object is phantom reachable. At that time it will atomically clear all phantom references to that object and all phantom references to any other phantom-reachable objects from which that object is reachable. At the same time or at some later time it will enqueue those newly-cleared phantom references that are registered with reference queues.
In order to ensure that a reclaimable object remains so, the referent of a phantom reference may not be retrieved: The
get
method of a phantom reference always returnsnull
.
如API文档所述,虚引用一般用来做事后清理。为了确保虚引用的referent成为可回收对象之后不被干扰能被顺利清理掉,PhantomReference的get方法直接返回null,而不会返回referent。
这就是虚引用与软引用、弱引用的最大区别。软引用和弱引用的referent变成弱可达之后,通过其get方法还是能够让referent恢复成强可达状态,但是PhantomReference直接堵死了这条路。
除此之外,PhantomReference只有一个构造函数,必须传入ReferenceQueue,以便在referent确定会被回收之后得到一个通知。
public class PhantomReference<T> extends Reference<T> {
/**
* Returns this reference object's referent. Because the referent of a
* phantom reference is always inaccessible, this method always returns
* {@code null}.
*
* @return {@code null}
*/
public T get() {
return null;
}
/**
* 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 {@code null}
* queue, but such a reference is completely useless: Its {@code get}
* me