Reference 引用类

  • WeakReference

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. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.
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. Since: 1.2

译:

弱引用对象,这些对象不会阻止对其引用对象进行终结,终结和回收。 弱引用最常用于实现映射。
假设垃圾收集器在某个时间点确定对象是弱可达的, 那么它将自动清除对该对象的所有弱引用,以及对所有其他弱可达对象的弱引用,这些对象都可以通过一系列强引用和软引用从该对象到达。 同时,它将声明所有以前弱对象都是可终结的。

同时或稍后它将添加那些已标注的新清除的弱引用至引用队列(Reference Queue)中

Constructor Summary:

WeakReference​(T referent)    
WeakReference​(T referent, ReferenceQueue<? super T> q)    

Description:

对于只有弱引用的对象来说,只要垃圾回收机制一运行,不管JVM的内存空间是否足够,都会回收该对象占用的内存。可以通过get()方法得到引用的对象。

Example:

 public static void main(String[] args) {
        Object o1 = new Object();
        WeakReference<Object> weakReference = new WeakReference<>(o1);
        System.out.println("------回收前------");
        System.out.println("o1:"+o1);
        System.out.println("weakReference:"+weakReference.get());

        o1 = null;
        System.gc();
        System.out.println("------回收后------");
        System.out.println("o1:"+o1);
        System.out.println("weakReference:"+weakReference.get());
        

    }

结果:

------回收前------
o1:java.lang.Object@4554617c
weakReference:java.lang.Object@4554617c
------回收后------
o1:null
weakReference:null

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/kongieg/p/11893335.html