了解下SoftReference

昨天同事看到别人一段关于实现缓存功能的代码,看完之后他有点不明觉厉,哈哈,然后就给周围同事也看了下,可能之前大家都没用过SoftReference,所以并不明白是如何实现的。

于是我就把代码要了过来,准备晚上回去看下,回家后做完饭,吃完饭,还顺便看了下恒大的比赛,之后想起来代码还没看,于是就打开电脑,开始琢磨他的代码。

那段代码其实就是实现了缓存功能,限量存储,且还带"定时删除"功能,我那个同事就在琢磨是咋定时删除的,我也想知道是咋删除的,下班前大概浏览了下代码,由于之前没用过SoftReference,所以还猜测是不是SoftReference有定时删除功能,但看了下SoftRefercence API好像没有这个功能。所以我回来后,就仔细浏览下写的代码,其实所谓的定时删除代码,并没有删除,而是代码里变通的用了个方法,在SoftReference所引用的对象上附加了一个超时时间值,所以在获取该对象值时,用当前时间与引用对象的超时时间进行对比,如果超时时间已经小于当前时间,那就认为该对象无效了,就实现了所谓的"定时删除"功能。

但琢磨不能仅限于此啊,为什么会用到SoftReference对象呢?

又google了相关SoftReference的介绍,发现果然很多都是说SoftReference是常在设计缓存时用到,而且也看到SoftReference jdk api中关于该类有一段介绍如下:

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。

也就是SoftReference所引用的对象会在内存不足时,由GC来裁决是否将其回收,它也最长被用来实现对内存敏感的缓存设计。

于是就想那到底啥时候会来回收呢?

搜到一遍很有价值的文章,看作者自我介绍时Google的一位牛人,还是JSR一员。文章地址

截取关键如下:

When a garbage collection occurs, the decision to clear a SoftReference is based on two factors:

  1. How old the reference's timestamp is, and
  2. How much free space there is in memory.

The calculation is pretty simple. If:

  • free_heap is the amount of free heap space in MB,
  • interval is the time between the last GC's clock and the timestamp of the ref we are currently examining, and
  • ms_per_mb is a constant number of milliseconds to keep around a SoftReference for each free megabyte in the heap

Then the decision is made by:

interval <= free_heap * ms_per_mb
原文地址:https://www.cnblogs.com/jadic/p/3597815.html