概述
自定义一个类
class Key {
//当该对象被 gc 回收的时候,会调用此方法
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("回收了"+Thread.currentThread().getId());
}
}
在Java中一般有两种引用类型:Reference类型 类型和普通引用类型
Reference 类型(都继承抽象 Reference 类):
-
SoftReference(软引用)
//当softReference包含的 key对象被回收以后,该 softReference 对象会放到referenceQueue队列中.
ReferenceQueue referenceQueue= new ReferenceQueue<>();
Key key = new Key();
SoftReference softReference=new SoftReference(key,referenceQueue);
key = null;当内存不足时,将会回收 Object 对象
-
WeakReference(弱引用)
ReferenceQueue referenceQueue= new ReferenceQueue<>();
Key key = new Key();
WeakReference weakReference=new WeakReference(key,referenceQueue);
key = null;
System.gc();当 gc 每一次就行垃圾回收的时候,如果检测到referenceQueue类型的对象时,就会将 Key 对象回收.当执行完system.gc()后,能够看到 Key 对象finalize()方法被调用,证明对象被回收
-
PhantomReference(虚引用)
ReferenceQueue referenceQueue= new ReferenceQueue<>(); Key key = new Key(); PhantomReference phantomReference= new PhantomReference(new key,referenceQueue); key = null;
PhantomReference一般用于调度回收前的清理的工作,只能依赖ReferenceQueue 一起使用.我们通过phantomReference.get()并不能得到Key 对象,只有对象被标记为不可达状态后(可以被回收),phantomReference 对象会被添加到referenceQueue队列中,当对象被垃圾回收起回收以后,phantomReference将会从队列中被移除
普通引用类型:
- 强引用类型 :Key key = new Key() 当没有任何引用指向该Key 对象的时候,gc 才能回收该对象
ReferenceQueue
在上面创建Reference对象的时候,我们看到都一个 referenceQueue对象,ReferenceQueue对象的主要用途是当softReference或者weakReference里的Key对象被垃圾回收器回收以后,softReference或者weakReference Reference对象会被添加到referenceQueue对类中,由于 Key 对象已经被回收,因此我们softReference或者weakReference.get()为 null.我们可以继承Reference类,为这个类添加一新的方法,比如添加一个被回收对象的名字或者得到回收对象的一些特性.
为什么需要 Reference 类?
我们知道在我们的程序运行的时候,如果一个gc 想要回收一个对象,必须保证该对象没有任何引用指向此对象,否则gc不能成功回收该对象.如果我们既想拥有该对象,又想让垃圾回收器回收对象的时候能够回收该对象,那就需要使用Reference对象,Reference 对象可以看做是对我们对象的包装,可以通过 Reference.set()方法把对象"包裹进去",当需要使用的时候通过 Reference.get()方法获取对象,当垃圾回收器进行垃圾回收时候,垃圾回收器能够根据不同类型的 Reference 派生类来决定是否回收 Reference 内包装的对象.
使用 Reference 场景和条件
场景:我们希望继续对某个对象持有应用,并且希望gc能够回收对象,那么就可以考虑使用 Reference 对象.
条件:必须保证只能通过 Reference 获得该对象,其他任何普通引用都没有指向该对象.