WeakReference

WeakReference


一、总结

1.jdk 1.8.0

2.定义
用来描述非必须的对象,但是它的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发送之前。当垃圾收集器工作时,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。一旦一个弱引用对象被垃圾回收器回收,便会加入到一个注册引用队列中。

3.
存活周期,第一次GC后到第二次GC前,第二次GC时被回收。
如果使用带有引用队列的构造方法,GC回收时弱引用被放入引用队列。

4.应用
WeakHashMap

二、源码分析

/**
 * 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.
 *
 * @version  1.19, 11/17/05
 * @author   Mark Reinhold
 * @since    1.2
 */

public class WeakReference<T> extends Reference<T> {

  • 弱引用对象,指的是不能防止他们的参照物对象终结、完成、再生
  • 弱引用通常是用来实现规范映射
  • 假设GC垃圾回收器在某一个时间点确认一个对象是弱可达,这时GC将会自动清除所有指向该对象的弱引用以及由强引用、软引用所链接的对象中出现的弱引用,同时GC将生命原来的所有的弱可达对象是终结的。同时或过一段时间会将新的弱引用对象放入引用队列中。



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



  • 对给定的对象创建弱引用对象,新的引用放入给定的队列中


三、弱引用

1.举例
// a 是 A 的强引用
A a = new A(); 
// b 对 a 的依赖
B b = new B(a);
// a 的引用指向 null 等待GC回收,但b持有对a的依赖,GC不能回收 a 对象
// 因为不能及时回收此类对象,可能造成内存泄漏
a = null ;
// 解决方案
b = null ; // 设置 a 的引用依赖为 null 
// 手动设置其引用依赖为NULL来解决 GC 回收的问题,违反了 GC 自动进行垃圾回收的理念

// 引入弱引用, B 继承 WeakRefence 
WeakRefence<A> wr = new WeakRefence<A>(a);
// 那么当 a = null 时,虽然依然被 b 引用依赖,但GC 依然可能回收此块的内存 


2.弱引用
当所引用的对象在 JVM 内不再有强引用时, GC 后 weak reference 将会被自动回收
对象只能生存到下一次垃圾收集之前。在垃圾收集器工作时,无论内存是否足够都会回收掉只被弱引用关联的对象。
博文参考:

谈谈java中的WeakReference



猜你喜欢

转载自mingyundezuoan.iteye.com/blog/2399609