可达性概述
- 当一个对象到 GC ROOT 不存在任何一条引用链的时候,表示此对象不可达,此对象会被判定为可回收对象。
- 以 GC ROOT 作为根节点,向下搜索走过的路径为引用链。
谁可以做 GC ROOT?
- 虚拟机栈中引用的对象
- 方法区中类静态属性引用的对象
- 方法区中常量引用的对象
- 本地方法区中 JNI 引用的对象
环状引用如何什么情况被回收?
JVM 计数器针对环装引用到达一定计数会执行回收。
引用类型分析
强引用
// 如果强引用一直存在,则对象不会被回收。
Object object=new Object();
软引用:还有用但是并非必须的对象
// 如果出现内存不足的时候,会 GC 软引用对象
// 继承下方法实现软引用对象
public class SoftReference<T> extends Reference<T> {
/**
* Timestamp clock, updated by the garbage collector
*/
static private long clock;
/**
* Timestamp updated by each invocation of the get method. The VM may use
* this field when selecting soft references to be cleared, but it is not
* required to do so.
*/
private long timestamp;
/**
* Creates a new soft reference that refers to the given object. The new
* reference is not registered with any queue.
*
* @param referent object the new soft reference will refer to
*/
public SoftReference(T referent) {
super(referent);
this.timestamp = clock;
}
/**
* Creates a new soft reference that refers to the given object and is
* registered with the given queue.
*
* @param referent object the new soft 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 SoftReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
this.timestamp = clock;
}
/**
* Returns this reference object's referent. If this reference object has
* been cleared, either by the program or by the garbage collector, then
* this method returns <code>null</code>.
*
* @return The object to which this reference refers, or
* <code>null</code> if this reference object has been cleared
*/
public T get() {
T o = super.get();
if (o != null && this.timestamp != clock)
this.timestamp = clock;
return o;
}
}
弱引用:比软引用更弱,被弱引用关联的对象存在周期是下次 GC 之前,和内存充足没有关联。
// 实现类
public class WeakReference<T> extends Reference<T> {
/**
* Creates a new weak reference that refers to the given object. The new
* reference is not registered with any queue.
*
* @param referent object the new weak reference will refer to
*/
public WeakReference(T referent) {
super(referent);
}
/**
* Creates a new weak reference that refers to the given object and is
* registered with the given queue.
*
* @param referent object the new weak 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 WeakReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
}
}
虚引用:最弱的一种引用方式,存在对生存时间没有影响,为对象设置虚引用关联的目的是能在对象被收集器回收的时候收到系统通知。
PhantomReference.java