一文搞懂强引用、软引用、弱引用和虚引用

Java中的引用类型分为四种:强引用软引用弱引用虚引用

强引用

例如:Object o = new Object()就是强引用关系,这是一种最为常见的引用关系,而被强引用关联的对象,只要引用关系还存在,则不会被垃圾收集器回收。

软引用

软引用一般关联的对象都有用但非必须的对象。被软引用关联的对象,在系统发生OOM前,会被垃圾收集器列入回收范围之中进行第二次回收,如若回收完依旧没有足够内存,则抛出内存溢出异常。
Java中使用SoftReference类实现软引用:

package java.lang.ref;


/**
 * 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.
 *
 * <p> Suppose that the garbage collector determines at a certain point in time
 * that an object is <a href="package-summary.html#reachability">softly
 * reachable</a>.  At that time it may choose to clear atomically all soft
 * references to that object and all soft references to any other
 * softly-reachable objects from which that object is reachable through a chain
 * of strong references.  At the same time or at some later time it will
 * enqueue those newly-cleared soft references that are registered with
 * reference queues.
 *
 * <p> All soft references to softly-reachable objects are guaranteed to have
 * been cleared before the virtual machine throws an
 * <code>OutOfMemoryError</code>.  Otherwise no constraints are placed upon the
 * time at which a soft reference will be cleared or the order in which a set
 * of such references to different objects will be cleared.  Virtual machine
 * implementations are, however, encouraged to bias against clearing
 * recently-created or recently-used soft references.
 *
 * <p> Direct instances of this class may be used to implement simple caches;
 * this class or derived subclasses may also be used in larger data structures
 * to implement more sophisticated caches.  As long as the referent of a soft
 * reference is strongly reachable, that is, is actually in use, the soft
 * reference will not be cleared.  Thus a sophisticated cache can, for example,
 * prevent its most recently used entries from being discarded by keeping
 * strong referents to those entries, leaving the remaining entries to be
 * discarded at the discretion of the garbage collector.
 *
 * @author   Mark Reinhold
 * @since    1.2
 */

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;
    }

}

从代码中可以得知,我们创建一个软引用对象的方式如下:

SoftReference<Object> softReference = new SoftReference<>(new Object());

因为软引用对象有可能会被清理掉,因此使用软引用对象时一般需要进行校验:

Object obj = softReference.get();
if( obj == null){
    softReference = new SoftReference<>(new Object());
}
obj = softReference.get();

其实也不难发现,软引用比较适合应用在需要缓存的场景,例如加载图片或者一些网络资源时。
软引用的被标记清理的原理与弱引用一致,参照弱引用中的解释。

弱引用

同样是用来描述非必须的对象,引用的强度比软引用更弱,被弱引用关联的对象,只能存在到下次垃圾收集发生为止。当垃圾收集开始,无论内存是否足够,弱引用关联的对象都将会被回收掉。
Java中使用WeakReference来实现弱引用:

package java.lang.ref;


/**
 * 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.
 *
 * <p> Suppose that the garbage collector determines at a certain point in time
 * that an object is <a href="package-summary.html#reachability">weakly
 * reachable</a>.  At that time it will atomically clear all weak references to
 * that object and all weak references to any other weakly-reachable objects
 * from which that object is reachable through a chain of strong and soft
 * references.  At the same time it will declare all of the formerly
 * weakly-reachable objects to be finalizable.  At the same time or at some
 * later time it will enqueue those newly-cleared weak references that are
 * registered with reference queues.
 *
 * @author   Mark Reinhold
 * @since    1.2
 */

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);
    }

}

使用方式与软引用也是类似的
重点关注一下使用场景,在Java中,为了确保某个对象会被垃圾收集器清理掉,我们常常会将引用置为null

Object obj = new Object();
obj = null;

当我们将obj设置为null时,原来指向的Object对象将没有强引用再指向他,因此,该对象是不可达的,将会被作为垃圾收集掉
其实一般情况下,随着方法执行完毕,大多数对象的引用都会随着方法栈的出栈而释放掉,而其指向的对象也就变为不可达的,因此无需手动将其设置为null
弱引用的使用场景最多的也是最为缓存来使用,我们定义需要缓存的对象

WeakReference<Object> weakReference = new WeakReference<>(new Object());

当我们需要引用时

Object o = weakReference.get();
if(o == null){
    weakReference = new WeakReference<>(new Object());
}
o = weakReference.get();

需要注意的是,此时o是作为强引用指向Object对象的,只要o的关联关系存在,那么Object对象是无法被回收的,当我们的方法出栈,或者说Object没有任何强引用关系,只存在弱引用关系时,在此期间如果没有其他强引用再次指向它,那么下次垃圾收集的时候,Object对象就会被作为垃圾清理掉。

虚引用

又称为幽灵引用幻影引用。它是引用关系中最弱的一个,虚引用的存在完全不会对对象的生存时间产生影响,同时我们也无法通过虚引用获取对象实例。使用虚引用关联的目的是:为了能够在该对象被回收时收到通知
在Java中使用PhantomReference实现虚引用

package java.lang.ref;


/**
 * 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.
 *
 * <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.
 *
 * <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>.
 *
 * <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.
 *
 * @author   Mark Reinhold
 * @since    1.2
 */

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</code>.
     *
     * @return  <code>null</code>
     */
    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 <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);
    }

}

源码中也印证了无法获得虚引用对象的说法,get方法始终都是返回null
同时也可以发现,虚引用只提供了一个构造方法

ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
PhantomReference<Object> phantomReference = new PhantomReference<>(new Object(), referenceQueue);

这种形式的构造方法在软引用弱引用中同样存在,ReferenceQueue是一个保存引用的队列,当引用关系发生改变时(被垃圾收集器收集),该引用会被添加到队列中
可以通过下面代码进行验证(软引用弱引用的不在列举):

ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
PhantomReference<Object> phantomReference = new PhantomReference<>(new Object(), referenceQueue);
Reference reference1;
while ((reference1 = referenceQueue.poll()) != null){
    System.out.println("reference1:"+ reference1);

}
System.gc();
TimeUnit.SECONDS.sleep(2);
Reference reference2;
while ((reference2 = referenceQueue.poll()) != null){
    System.out.println("reference2:"+reference2);
}

执行结果:reference2:java.lang.ref.PhantomReference@6b884d57
gc发生是,Object对象被垃圾收集器回收掉,同时引用信息会被保存到referenceQueue队列中,但是因为PhantomReferenceget方法返回的都是null,因此即便可以将虚引用对象出队,也是没有任何意义的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java.util.Man

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值