Reference 引用类

 

Reference Queue

 


 

public class ReferenceQueue<T>
extends Object
Reference queues, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected.
Since:
1.2
  • Method Summary:

Reference<? extends T>    poll()    
Reference<? extends T>    remove()    
Reference<? extends T>    remove​(long timeout)    

 

 

Reference

 


 

Direct Known Subclasses:
PhantomReference, SoftReference, WeakReference
public abstract class Reference<T> extends Object Abstract base class for reference objects. This class defines the operations common to all reference objects. Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly. Since: 1.2
  • Method Summary:

void         clear()    
boolean      enqueue()    
T          get()    
boolean      isEnqueued()
static void dreachabilityFence​(Object ref)

void():Clears this reference object.

enqueue():

Adds this reference object to the queue with which it is registered, if any.---jdk8

Clears this reference object and adds it to the queue with which it is registered, if any.---jdk10

get():Returns this reference object's referent.

isEnqueued():Tells whether or not this reference object has been enqueued, either by the program or by the garbage collector.

  • Description:

Reference是一个抽象类,已知的子类有软引用(Softreference),弱引用(WeakReference)和虚引用(PhantomReference)

SoftReference


 

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.
All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError. 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.

 

译:

软引用对象,垃圾回收器会根据内存需求酌情清除这些对象。 软引用最常用于实现对内存敏感的缓存。
每个软引用都保证允许自身在JVM在抛出OOM错误之前进行被GC清理。
  • Constructor Summary

SoftReference(T referent)
Creates a new soft reference that refers to the given object.
SoftReference(T referent, ReferenceQueue<? super T> q)
Creates a new soft reference that refers to the given object and is registered with the given queue.
  • Method Summary

public T get()
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 null.

 

  • 使用场景

假如有一个应用需要读取大量的本地图片:
如果每次读取土拍你都会从硬盘读取则会严重影响性能
如果一次性全部加载到内存中又可能造成内存溢出
  • Example

public static void main(String[] args) {
        Car car = new Car("1","2");
        ReferenceQueue referenceQueue = new ReferenceQueue();
        SoftReference<Car> softReference = new SoftReference<>(car);
        Car dreamCar = null;
        
        if(softReference.get() != null){
            dreamCar = softReference.get();
        }else{
            car = new Car("1","2");
            softReference = new SoftReference<>(car);
            dreamCar = softReference.get();
        }
    }

 

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:

  1. 对于只有弱引用的对象来说,只要垃圾回收机制一运行,不管JVM的内存空间是否足够,都会回收该对象占用的内存。可以通过get()方法得到引用的对象。
  2. 弱引用可以配合引用队列(Reference Queue)使用,当弱引用对象被GC时,会将此对象添加至引用队列中。
  3. 引用队列可被多个弱引用对象使用;每次执行poll()方法会从队列中取出顶部的弱引用对象,但是调用该弱引用对象的get()方法得到是Null。
  4. 引用队列不可以从中获取弱引用对象,唯一的用途是证明弱引用对象"曾经来过"。
  • Example:

public static void main(String[] args) {
        Car car1 = new Car("1","1");
        Car car2 = new Car("2","2");
        ReferenceQueue referenceQueue = new ReferenceQueue();
        WeakReference<Car> weakReference = new WeakReference<>(car1,referenceQueue);
        WeakReference<Car> weakReference2 = new WeakReference<>(car2,referenceQueue);
        System.out.println("------回收前------");
        System.out.println("car1:"+car1);
        System.out.println("weakReference:"+weakReference.get());
        System.out.println("weakReference2:"+weakReference2.get());
        System.out.println("referenceQueue:"+referenceQueue.poll());
        car1 = null;
        car2 = null;
        System.gc();
        System.out.println("------回收后------");
        System.out.println("car1:"+car1);
        System.out.println("car2:"+car2);
        System.out.println("weakReference:"+weakReference.get());
        System.out.println("weakReference2:"+weakReference2.get());
        System.out.println("referenceQueue第一次被poll的值:"+referenceQueue.poll());
        System.out.println("referenceQueue第二次被poll的值:"+referenceQueue.poll());
        System.out.println("referenceQueue第三次被poll的值:"+referenceQueue.poll());

    }

 

执行结果:

------回收前------
car1:Car{name='1', speed='1'}
weakReference:Car{name='1', speed='1'}
weakReference2:Car{name='2', speed='2'}
referenceQueue:null
------回收后------
car1:null
car2:null
weakReference:null
weakReference2:null
referenceQueue第一次被poll的值:java.lang.ref.WeakReference@4554617c
referenceQueue第二次被poll的值:java.lang.ref.WeakReference@74a14482
referenceQueue第三次被poll的值:null

Process finished with exit code 0
  • 使用场景:

 【如果这个对象是偶尔的使用,并且希望在使用时随时就能获取到,但又不想影响此对象的垃圾收集,那么你应该用 Weak Reference 来记住此对象。】摘自gudi

PhantomReference


顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。
如果一个对象仅持有虚拟用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收,它不能单独使用也不能通过它访问对象,虚引用必须和引用队列(ReferenceQuene)联合使用。
虚引用的主要作用是跟踪对象被垃圾回收的状态。仅仅是提供了一种确保对象被finalize以后,做某些事情的机制,
PhantomReference的get方法总是返回null,因此无法访问对应的引用的对象。其意义在于说明一个对象已经进入finalization阶段,可以被gc回收,用来实现比finalization机制更灵活的回收操作。
换句话说,设置虚引用关联的唯一目的,就是在这个对象被收集器回收的时候收到一个系统通知或者后续添加进一步的处理。
Java技术允许使用finalize()方法在垃圾收集器将对象从内存中清除出去之前做必要的清理工作。

 

 

 

 

 

posted on 2019-11-19 23:09  kongieg  阅读(361)  评论(0编辑  收藏  举报