Java ~ Reference ~ SoftReference
admin
2024-01-20 21:19:36
0

一 概述


    SoftReference(软引用)类是Reference(引用)类的四大子类之一,只被SoftReference(软引用)类对象持有的对象(即被作为所指对象)被称为软可达(softly reachable)对象。在Java中关于软引用的定义是:如果一个对象只存在软引用,则其在空闲内存充裕的情况下不一定会被GC回收,具体情况视回收策略而定。而如果GC回收后空闲内存依旧不足,便会强制回收软可达(softly reachable)对象则会被以避免OOM。虚拟机在抛出OOM错误前会保证清除所有的软可达(softly reachable)对象。

    SoftReference(软引用)类适合用于做缓存。软引用适合做缓存是因为其自身可有可无的引用强度决定的,缓存是加快程序的运行效率而非正常运行的必要条件,即使是在没有共存强引用的环境下,只要空闲内存充裕,软引用自身也能够保证热点数据持久存在,这与缓存的运用场景是高度契合的。因此使用SoftReference(软引用)类制作缓存一方面充分利用了空闲内存加快程序的运行效率,另一方面也在空闲内存不足时将仅有的内存资源用于保障程序的正常运行而非浪费在可有可无的地方。

二 源码及机制详解


 类

    SoftReference(软引用)类继承自Reference(引用)类。当一个SoftReference(软引用)类对象被GC判断该为可回收时,会选择性(会根据回收策略清除其中的一部分)的自动清除清除当前软可达对象及持有其强引用链的软可达对象的所有软引用。

/*** 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.* 软引用对象,垃圾收集器根据内存需求自行清除这些对象。软引用最常用于实现对内存敏感的缓存。* 

* Suppose that the garbage collector determines at a certain point in time* that an object is softly* reachable. 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.* 假设垃圾收集器在某个时间点确定一个对象是软可达的。那时,它会选择性的自动清除对该对象的所有软引用,* 以及对任何其它软可达对象的所有软引用,而该对象可以通过强引用链访问。在同一时间或稍后的某个时间,* 它将对那些注册在引用队列中的新清除的软引用进行入队。*

* 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.* 对软可达对象的所有软引用保证在虚拟机抛出OOM之前已被清除。* 虽然对清除软引用的时间或清除对不同对象的这类引用集合的顺序没有任何约束。* 但鼓励虚拟机实现不清除最近创建或最近使用的软引用。*

* 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 extends Reference {... }

 字段

    clock(时钟) —— 静态变量,由全局共享。本质是上次GC回收的时间戳,该值由GC负责更新。

/*** Timestamp clock, updated by the garbage collector*/
static private long clock;

    timestamp(时间戳) —— 当通过get()方法获取所指对象且所指对象不为null时该值会被更新为clock(时钟)字段值。该值被作为软可达(softly reachable)对象是否被GC回收的判断依据,具体做法是将clock(时钟)字段值减去timestamp(时间戳)字段值的差作为软可达(softly reachable)对象上次使用距离当前时间的近似值,并判断该值是否大于最大间隔,是则回收,否则保留。

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

 构造方法

    public SoftReference(T referent) —— 只设置所指对象而不设置引用队列,因此可知SoftReference(软引用)类可不搭配引用队列使用。

/*** 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);// 时间戳和时钟的初始值都是0。this.timestamp = clock;
}

    public SoftReference(T referent, ReferenceQueue q) —— 同时设置所指对象及引用队列。

/*** 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 null if registration is not required*/
public SoftReference(T referent, ReferenceQueue q) {super(referent, q);this.timestamp = clock;
}

 方法

    public T get() —— 获取所指对象 —— 获取SoftReference(软引用)类对象的所指对象。当所指对象不为null时更新timestamp(时间戳)字段值为clock(时钟)字段值,作为GC判断软可达(softly reachable)对象是否回收的依据。

/*** 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.** @return The object to which this reference refers, or* null if this reference object has been cleared* @Description: 获取所指对象*/
@Override
public T get() {T o = super.get();// 当所指对象不为空且时间戳不等于时钟时,更新时间戳的值。if (o != null && this.timestamp != clock)this.timestamp = clock;return o;
}

三 回收策略


    回收策略是在空闲内存充裕的情况下用于回收软可达(softly-reachable)对象的规则。最近最少使用当前堆策略(LRUCurrentHeapPolicy)的全称为Least Recently Used Current Heap Policy,是最常用的回收策略。其思想是只保留使用最为频繁的部分软可达(softly reachable)对象,而将使用不频繁甚至不使用的软可达(softly reachable)对象回收。具体做法是计算软可达(softly reachable)对象的上次获取时间距离当前时间的间隔,并与最大间隔作比较,判断间隔是否小于等于最大间隔,是则保留,否则回收。其中最大间隔 = 空闲堆内存(MB) * JVM参数-XX:SoftRefLRUPolicyMSPerMB(默认值1000ms),故如果假设空闲堆内存为400MB,则可得最大间隔的值为400秒,当软可达(softly reachable)对象的间隔大于400秒时便会被GC回收。具体源码如下:

bool LRUCurrentHeapPolicy::should_clear_reference(oop p, jlong timestamp_clock) {// 使用时钟 - 时间戳得到差值,这个差值可以近似代表软可达(softly reachable)对象上次被获取时间至当前时间的间隔。jlong interval = timestamp_clock - java_lang_ref_SoftReference::timestamp(p);assert(interval >= 0, "Sanity check");// 如果间隔 <= 最大间隔,则不进行回收。if(interval <= _max_interval) {return false;}// 如果间隔 > 最大间隔,则进行回收。return true;
}
void LRUCurrentHeapPolicy::setup() {// 最大间隔 = 空闲堆内存(MB) * 每MB空闲内存保留时间。_max_interval = (Universe::get_heap_free_at_last_gc() / M) * SoftRefLRUPolicyMSPerMB;assert(_max_interval >= 0,"Sanity check");
}

四 JVM参数


  • -XX:SoftRefLRUPolicyMSPerMB —— 设置每MB空闲内存的单位保留时间。默认1000毫秒。

五 相关系列


  • 《Java ~ Reference》
  • 《Java ~ Reference ~ ReferenceQueue》
  • 《Java ~ Reference ~ SoftReference》
  • 《Java ~ Reference ~ PhantomReference/Cleaner》
  • 《Java ~ Reference ~ FinalReference/Finalizer》

相关内容

热门资讯

安卓系统的地图怎样下载,下载与... 你有没有发现,现在不管去哪里,手机地图都成了我们的好帮手?尤其是安卓系统的地图,功能强大,用起来超级...
安卓9.0系统挂机游戏,轻松享... 你有没有发现,自从安卓9.0系统更新后,手机里的游戏体验简直就像坐上了火箭!今天,就让我带你一起探索...
安卓系统怎么用迅雷下载,安卓系... 你有没有想过,在安卓系统上下载文件竟然也能这么简单?没错,今天就要来给你揭秘,如何用迅雷在安卓系统上...
安卓手机刷成学生系统,探索全新... 你有没有想过,你的安卓手机其实可以变身成一个充满学习氛围的学生系统呢?没错,就是那种看起来简洁、功能...
ios能迁移安卓系统吗,iOS... 你有没有想过,你的iPhone里的那些宝贝应用,能不能搬到安卓手机上继续使用呢?这可是不少手机用户的...
荣耀10安卓11系统,畅享极致... 你知道吗?最近手机界可是热闹非凡呢!荣耀10这款手机,自从升级到了安卓11系统,简直就像脱胎换骨了一...
安卓系统pc版电脑配置,打造流... 你有没有想过,安卓系统竟然也能在电脑上运行呢?没错,就是那个我们手机上常用的安卓系统,现在也能在PC...
tcllinux系统刷安卓系统... 你有没有想过,你的TCL Linux系统竟然也能升级成安卓系统呢?没错,就是那个我们日常使用的安卓系...
安卓13系统更新蓝牙,蓝牙功能... 你有没有发现,最近你的安卓手机好像变得不一样了?没错,就是那个神秘的安卓13系统更新,它悄悄地来到了...
安卓系统钉钉打开声音,安卓系统... 你有没有遇到过这种情况?手机里装了钉钉,可每次打开它,那声音就“嗖”地一下跳出来,吓你一跳。别急,今...
理想汽车操作系统安卓,基于安卓... 你有没有想过,一辆汽车,除了能带你去你想去的地方,还能像智能手机一样,给你带来智能化的体验呢?没错,...
安卓系统越狱还能升级吗,升级之... 你有没有想过,你的安卓手机越狱后,还能不能愉快地升级系统呢?这可是不少手机爱好者关心的大问题。今天,...
安卓系统蓝牙耳机拼多多,畅享无... 你有没有发现,最近蓝牙耳机在市场上可是火得一塌糊涂呢!尤其是安卓系统的用户,对于蓝牙耳机的要求那可是...
安卓变苹果系统桌面,桌面系统变... 你知道吗?最近有个大新闻在科技圈里炸开了锅,那就是安卓用户纷纷转向苹果系统桌面。这可不是闹着玩的,这...
鸿蒙系统怎么下安卓,鸿蒙系统下... 你有没有想过,你的手机里那个神秘的鸿蒙系统,竟然也能和安卓世界来一场亲密接触呢?没错,今天就要来揭秘...
手机安卓系统流程排行,便捷操作... 你有没有发现,现在手机的世界里,安卓系统就像是个大舞台,各种版本层出不穷,让人眼花缭乱。今天,就让我...
安卓系统左上角hd,左上角HD... 你有没有发现,每次打开安卓手机,左上角那个小小的HD标识总是默默地在那里,仿佛在诉说着什么?今天,就...
安卓系统软件文件,架构解析与功... 你有没有发现,手机里的安卓系统软件文件就像是一个神秘的宝库,里面藏着无数的宝藏?今天,就让我带你一起...
安卓系统输入法回车,探索安卓输... 你有没有发现,在使用安卓手机的时候,输入法回车键的奇妙之处?它就像是我们指尖的魔法师,轻轻一点,文字...
安卓修改系统时间的软件,轻松掌... 你有没有想过,有时候手机上的时间不对劲,是不是觉得生活节奏都被打乱了?别急,今天就来给你揭秘那些神奇...