- 强引用
- 软引用
- 弱引用
- 虚引用
强引用
Strongly Reference
指在程序代码之中普遍存在的引用赋值,即:Object obj = new Object()
。
无论任何情况下,只要强引用关系还存在,垃圾收集器就永远不会回收掉被引用的对象。
软引用
Soft Reference
描述一些还有用,但非必须的对象。
只被软引用关联着的对象,在系统将要发生内存溢出一场前,会把这些对象列进回收范围之中进行第二次回收,如果这次回收还没有足够的内存,才会抛出内存溢出异常。
/**
* Soft reference objects, which are cleared at the discretion of the garbage
* collector in response to memory demand. Soft references are most often used
* to implement memory-sensitive caches.*/
public class SoftReference<T> extends Reference<T> {
}
弱引用
Weak Reference
描述非必须对象,但它的强度比软引用更弱一些。
被弱引用关联的对象只能生存到下一次垃圾收集发生为止。
当垃圾收集器开始工作,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。
/**
* Weak reference objects, which do not prevent their referents from being
* made finalizable, finalized, and then reclaimed. Weak references are most
* often used to implement canonicalizing mappings.
*/
public class WeakReference<T> extends Reference<T> {
}
虚引用
“幽灵引用”/“幻影引用”
Phantom reference
/**
* 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.
*/
public class PhantomReference<T> extends Reference<T> {
}
最弱的一种引用关系。
一个对象是否有虚引用的存在,完全不会对其生存时间构成影响,也无法通过虚引用来取得一个对象实例。
为一个对象设置虚引用关联的唯一目的只是为了能在这个对象被收集器回收时收到一个系统通知。
来源《深入理解Java虚拟机·JVM高级特性与最佳实践(第三版)》