当前位置: 首页 > news >正文

Android提供的LruCache类简介(1)

  1. If your cached values hold resources that need to be explicitly released,

  2. * override {@link #entryRemoved}.

  3. * 如果你cache的某个值需要明确释放,重写entryRemoved()

  4. If a cache miss should be computed on demand for the corresponding keys,

  5. * override {@link #create}. This simplifies the calling code, allowing it to

  6. * assume a value will always be returned, even when there’s a cache miss.

  7. * 如果key相对应的item丢掉啦,重写create().这简化了调用代码,即使丢失了也总会返回。

  8. By default, the cache size is measured in the number of entries. Override

  9. * {@link #sizeOf} to size the cache in different units. For example, this cache

  10. * is limited to 4MiB of bitmaps: 默认cache大小是测量的item的数量,重写sizeof计算不同item的

  11. *  大小。

  12.    {@code

  13. *   int cacheSize = 4 * 1024 * 1024; // 4MiB

  14. *   LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {

  15. *       protected int sizeOf(String key, Bitmap value) {

  16. *           return value.getByteCount();

  17. *       }

  18. *   }}

  19. *

  20. This class is thread-safe. Perform multiple cache operations atomically by

  21. * synchronizing on the cache: 

       {@code

  22. *   synchronized (cache) {

  23. *     if (cache.get(key) == null) {

  24. *         cache.put(key, value);

  25. *     }

  26. *   }}

  27. *

  28. This class does not allow null to be used as a key or value. A return

  29. * value of null from {@link #get}, {@link #put} or {@link #remove} is

  30. * unambiguous: the key was not in the cache.

  31. * 不允许key或者value为null

  32. *  当get(),put(),remove()返回值为null时,key相应的项不在cache中

  33. */

  34. public class LruCache<K, V> {

  35. private final LinkedHashMap<K, V> map;

  36. /** Size of this cache in units. Not necessarily the number of elements. */

  37. private int size; //已经存储的大小

  38. private int maxSize; //规定的最大存储空间

  39. private int putCount;  //put的次数

  40. private int createCount;  //create的次数

  41. private int evictionCount;  //回收的次数

  42. private int hitCount;  //命中的次数

  43. private int missCount;  //丢失的次数

  44. /**

  45. * @param maxSize for caches that do not override {@link #sizeOf}, this is

  46. *     the maximum number of entries in the cache. For all other caches,

  47. *     this is the maximum sum of the sizes of the entries in this cache.

  48. */

  49. public LruCache(int maxSize) {

  50. if (maxSize <= 0) {

  51. throw new IllegalArgumentException(“maxSize <= 0”);

  52. }

  53. this.maxSize = maxSize;

  54. this.map = new LinkedHashMap<K, V>(0, 0.75f, true);

  55. }

  56. /**

  57. * Returns the value for {@code key} if it exists in the cache or can be

  58. * created by {@code #create}. If a value was returned, it is moved to the

  59. * head of the queue. This returns null if a value is not cached and cannot

  60. * be created. 通过key返回相应的item,或者创建返回相应的item。相应的item会移动到队列的头部,

  61. * 如果item的value没有被cache或者不能被创建,则返回null。

  62. */

  63. public final V get(K key) {

  64. if (key == null) {

  65. throw new NullPointerException(“key == null”);

  66. }

  67. V mapValue;

  68. synchronized (this) {

  69. mapValue = map.get(key);

  70. if (mapValue != null) {

  71. hitCount++;  //命中

  72. return mapValue;

  73. }

  74. missCount++;  //丢失

  75. }

  76. /*

  77. * Attempt to create a value. This may take a long time, and the map

  78. * may be different when create() returns. If a conflicting value was

  79. * added to the map while create() was working, we leave that value in

  80. * the map and release the created value.

  81. * 如果丢失了就试图创建一个item

  82. */

  83. V createdValue = create(key);

  84. if (createdValue == null) {

  85. return null;

  86. }

  87. synchronized (this) {

  88. createCount++;//创建++

  89. mapValue = map.put(key, createdValue);

  90. if (mapValue != null) {

  91. // There was a conflict so undo that last put

  92. //如果前面存在oldValue,那么撤销put()

  93. map.put(key, mapValue);

  94. } else {

  95. size += safeSizeOf(key, createdValue);

  96. }

  97. }

  98. if (mapValue != null) {

  99. entryRemoved(false, key, createdValue, mapValue);

  100. return mapValue;

  101. } else {

  102. trimToSize(maxSize);

  103. return createdValue;

  104. }

  105. }

  106. /**

  107. * Caches {@code value} for {@code key}. The value is moved to the head of

  108. * the queue.

  109. *

  110. * @return the previous value mapped by {@code key}.

  111. */

  112. public final V put(K key, V value) {

  113. if (key == null || value == null) {

  114. throw new NullPointerException(“key == null || value == null”);

  115. }

  116. V previous;

  117. synchronized (this) {

  118. putCount++;

  119. size += safeSizeOf(key, value);

  120. previous = map.put(key, value);

  121. if (previous != null) {  //返回的先前的value值

  122. size -= safeSizeOf(key, previous);

  123. }

  124. }

  125. if (previous != null) {

  126. entryRemoved(false, key, previous, value);

  127. }

  128. trimToSize(maxSize);

  129. return previous;

  130. }

  131. /**

  132. * @param maxSize the maximum size of the cache before returning. May be -1

  133. *     to evict even 0-sized elements.

  134. *  清空cache空间

  135. */

  136. private void trimToSize(int maxSize) {

  137. while (true) {

  138. K key;

  139. V value;

  140. synchronized (this) {

  141. if (size < 0 || (map.isEmpty() && size != 0)) {

  142. throw new IllegalStateException(getClass().getName()

  143. + “.sizeOf() is reporting inconsistent results!”);

  144. }

  145. if (size <= maxSize) {

  146. break;

  147. }

  148. Map.Entry<K, V> toEvict = map.eldest();

  149. if (toEvict == null) {

  150. break;

  151. }

  152. key = toEvict.getKey();

  153. value = toEvict.getValue();

  154. map.remove(key);

  155. size -= safeSizeOf(key, value);

  156. evictionCount++;

  157. }

  158. entryRemoved(true, key, value, null);

  159. }

  160. }

  161. /**

  162. * Removes the entry for {@code key} if it exists.

  163. * 删除key相应的cache项,返回相应的value

  164. * @return the previous value mapped by {@code key}.

  165. */

  166. public final V remove(K key) {

  167. if (key == null) {

  168. throw new NullPointerException(“key == null”);

  169. }

  170. V previous;

  171. synchronized (this) {

  172. previous = map.remove(key);

  173. if (previous != null) {

  174. size -= safeSizeOf(key, previous);

  175. }

  176. }

  177. if (previous != null) {

  178. entryRemoved(false, key, previous, null);

  179. }

  180. return previous;

  181. }

  182. /**

  183. * Called for entries that have been evicted or removed. This method is

  184. * invoked when a value is evicted to make space, removed by a call to

  185. * {@link #remove}, or replaced by a call to {@link #put}. The default

  186. * implementation does nothing.

  187. * 当item被回收或者删掉时调用。改方法当value被回收释放存储空间时被remove调用,

  188. * 或者替换item值时put调用,默认
    实现什么都没做。

  189. The method is called without synchronization: other threads may

  190. * access the cache while this method is executing.

  191. *

  192. * @param evicted true if the entry is being removed to make space, false

  193. *     if the removal was caused by a {@link #put} or {@link #remove}.

  194. * true—为释放空间被删除;false—put或remove导致

  195. * @param newValue the new value for {@code key}, if it exists. If non-null,

  196. *     this removal was caused by a {@link #put}. Otherwise it was caused by

  197. *     an eviction or a {@link #remove}.

  198. */

  199. protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}

  200. /**

  201. * Called after a cache miss to compute a value for the corresponding key.

  202. * Returns the computed value or null if no value can be computed. The

  203. * default implementation returns null.

  204. * 当某Item丢失时会调用到,返回计算的相应的value或者null

  205. The method is called without synchronization: other threads may

  206. * access the cache while this method is executing.

  207. *

  208. If a value for {@code key} exists in the cache when this method

  209. * returns, the created value will be released with {@link #entryRemoved}

  210. * and discarded. This can occur when multiple threads request the same key

  211. * at the same time (causing multiple values to be created), or when one

  212. * thread calls {@link #put} while another is creating a value for the same

  213. * key.

  214. */

  215. protected V create(K key) {

  216. return null;

  217. }

  218. private int safeSizeOf(K key, V value) {

  219. int result = sizeOf(key, value);

  220. if (result < 0) {

  221. throw new IllegalStateException("Negative size: " + key + “=” + value);

  222. }

  223. return result;

  224. }

  225. /**

  226. * Returns the size of the entry for {@code key} and {@code value} in

  227. * user-defined units.  The default implementation returns 1 so that size

  228. * is the number of entries and max size is the maximum number of entries.

  229. * 返回用户定义的item的大小,默认返回1代表item的数量,最大size就是最大item值

  230. An entry’s size must not change while it is in the cache.

  231. */

  232. protected int sizeOf(K key, V value) {

  233. return 1;

  234. }

  235. /**

  236. * Clear the cache, calling {@link #entryRemoved} on each removed entry.

最后

小编这些年深知大多数初中级Android工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人

都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

资料⬅专栏获取
0.      */

  1. protected int sizeOf(K key, V value) {

  2. return 1;

  3. }

  4. /**

  5. * Clear the cache, calling {@link #entryRemoved} on each removed entry.

最后

小编这些年深知大多数初中级Android工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。

[外链图片转存中…(img-7R2o989d-1718991877996)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人

都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

资料⬅专栏获取

http://www.lryc.cn/news/379095.html

相关文章:

  • 【分布式系列】分布式锁timeout了怎么办?
  • System.getProperty()方法总结
  • 大型语言模型在AMD GPU上的推理优化
  • Apple - Core Foundation Design Concepts
  • lua中的lfs库介绍
  • PyCharm 快捷键积累
  • C++进阶之AVL树
  • sizeof 和 strlen 比较
  • 音视频开发—FFmpeg 打开摄像头进行RTMP推流
  • D触发器(D Flip-Flop)与D锁存器(D Latch)
  • JDK19特性
  • sql语句中常用的函数有那些
  • odoo17 小变更3 Warning、 “attrs “和 “states “不再用
  • Unity3d 游戏暂停(timeScale=0)引起的deltaTime关联的系列问题解决
  • 服务端代码编写中MySql大小写在Java中报错问题解决
  • CRMEB 多店商品详情页装修说明
  • Redis-使用 jedis 操作数据
  • 简说PIP换源
  • django学习入门系列之第三点《CSS基础样式介绍2》
  • 分布式光纤测温DTS在工程现场中稳定性与可靠性如何?
  • PHP多线程模块parallel的编译安装和多线程编程演示
  • 记录grid布局属性
  • 12.爬虫---PyMysql安装与使用
  • VS2022遇到的两个问题
  • 【Android14 ShellTransitions】(六)SyncGroup完成
  • 技术管理转型之战:决策之道-管理中的智慧与策略
  • Shell脚本:条件语句(if、case)
  • 在Linux上为Windows目标配置Qt交叉编译
  • Introduction to linear optimization 第 2 章课后题答案 11-15
  • Java——包