Android緩存機(jī)制——LruCache的詳解
概述
LruCache的核心原理就是對(duì)LinkedHashMap的有效利用,它的內(nèi)部存在一個(gè)LinkedHashMap成員變量,值得注意的4個(gè)方法:構(gòu)造方法、get、put、trimToSize
LRU(Least Recently Used)緩存算法便應(yīng)運(yùn)而生,LRU是最近最少使用的算法,它的核心思想是當(dāng)緩存滿時(shí),會(huì)優(yōu)先淘汰那些最近最少使用的緩存對(duì)象。采用LRU算法的緩存有兩種:LrhCache和DisLruCache,分別用于實(shí)現(xiàn)內(nèi)存緩存和硬盤緩存,其核心思想都是LRU緩存算法。
LRU原理
LruCache的核心思想很好理解,就是要維護(hù)一個(gè)緩存對(duì)象列表,其中對(duì)象列表的排列方式是按照訪問順序?qū)崿F(xiàn)的,即一直沒訪問的對(duì)象,將放在隊(duì)頭,即將被淘汰。而最近訪問的對(duì)象將放在隊(duì)尾,最后被淘汰。(隊(duì)尾添加元素,隊(duì)頭刪除元素)
LruCache 其實(shí)使用了 LinkedHashMap 雙向鏈表結(jié)構(gòu),現(xiàn)在分析下 LinkedHashMap 使用方法。
1.構(gòu)造方法:
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
當(dāng) accessOrder 為 true 時(shí),這個(gè)集合的元素順序就會(huì)是訪問順序,也就是訪問了之后就會(huì)將這個(gè)元素放到集合的最后面。
例如:
LinkedHashMap < Integer, Integer > map = new LinkedHashMap < > (0, 0.75f, true);
map.put(0, 0);
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.get(1);
map.get(2);
for (Map.Entry < Integer, Integer > entry: map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
輸出結(jié)果:
0:0
3:3
1:1
2:2
下面我們?cè)贚ruCache源碼中具體看看,怎么應(yīng)用LinkedHashMap來實(shí)現(xiàn)緩存的添加,獲得和刪除的:
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this cache.
*/
public LruCache(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
this.maxSize = maxSize;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);//accessOrder被設(shè)置為true
}
從LruCache的構(gòu)造函數(shù)中可以看到正是用了LinkedHashMap的訪問順序。
2.put()方法
/**
* Caches {@code value} for {@code key}. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by {@code key}.
*/
public final V put(K key, V value) {
if (key == null || value == null) {//判空,不可為空
throw new NullPointerException("key == null || value == null");
}
V previous;
synchronized (this) {
putCount++;//插入緩存對(duì)象加1
size += safeSizeOf(key, value);//增加已有緩存的大小
previous = map.put(key, value);//向map中加入緩存對(duì)象
if (previous != null) {//如果已有緩存對(duì)象,則緩存大小恢復(fù)到之前
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {//entryRemoved()是個(gè)空方法,可以自行實(shí)現(xiàn)
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);//調(diào)整緩存大小(關(guān)鍵方法)
return previous;
}
可以看到put()方法重要的就是在添加過緩存對(duì)象后,調(diào)用 trimToSize()方法來保證內(nèi)存不超過maxSize
3.trimToSize方法
再看一下trimToSize()方法:
/**
* Remove the eldest entries until the total of remaining entries is at or
* below the requested size.
*
* @param maxSize the maximum size of the cache before returning. May be -1
* to evict even 0-sized elements.
*/
public void trimToSize(int maxSize) {
while (true) {//死循環(huán)
K key;
V value;
synchronized (this) {
//如果map為空并且緩存size不等于0或者緩存size小于0,拋出異常
if (size < 0 || (map.isEmpty() && size != 0)) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
//如果緩存大小size小于最大緩存,或者map為空,不需要再刪除緩存對(duì)象,跳出循環(huán)
if (size <= maxSize) {
break;
}
// 取出 map 中最老的映射
Map.Entry<K, V> toEvict = map.eldest();
if (toEvict == null) {
break;
}
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
trimToSize()方法不斷地刪除LinkedHashMap中隊(duì)頭的元素,即近期最少訪問的,直到緩存大小小于最大值。
4. get方法
當(dāng)調(diào)用LruCache的get()方法獲取集合中的緩存對(duì)象時(shí),就代表訪問了一次該元素,將會(huì)更新隊(duì)列,保持整個(gè)隊(duì)列是按照訪問順序排序。這個(gè)更新過程就是在LinkedHashMap中的get()方法中完成的。
接著看LruCache的get()方法
/**
* Returns the value for {@code key} if it exists in the cache or can be
* created by {@code #create}. If a value was returned, it is moved to the
* head of the queue. This returns null if a value is not cached and cannot
* be created.
*/
public final V get(K key) {
if (key == null) {//key不能為空
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
/獲取對(duì)應(yīng)的緩存對(duì)象
mapValue = map.get(key);
if (mapValue != null) {
hitCount++;
return mapValue;
}
missCount++;
}
看到LruCache的get方法實(shí)際是調(diào)用了LinkedHashMap的get方法:
public V get(Object key) {
LinkedHashMapEntry<K,V> e = (LinkedHashMapEntry<K,V>)getEntry(key);
if (e == null)
return null;
e.recordAccess(this);//實(shí)現(xiàn)排序的關(guān)鍵
return e.value;
}
再接著看LinkedHashMapEntry的recordAccess方法:
/**
* This method is invoked by the superclass whenever the value
* of a pre-existing entry is read by Map.get or modified by Map.set.
* If the enclosing Map is access-ordered, it moves the entry
* to the end of the list; otherwise, it does nothing.
*/
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {//判斷是否是訪問順序
lm.modCount++;
remove();//刪除此元素
addBefore(lm.header);//將此元素移到隊(duì)尾
}
}
recordAccess方法的作用是如果accessOrder為true,把已存在的entry在調(diào)用get讀取或者set編輯后移到隊(duì)尾,否則不做任何操作。
也就是說: 這個(gè)方法的作用就是將剛訪問過的元素放到集合的最后一位
總結(jié):
LruCache的核心原理就是對(duì)LinkedHashMap 對(duì)象的有效利用。在構(gòu)造方法中設(shè)置maxSize并將accessOrder設(shè)為true,執(zhí)行g(shù)et后會(huì)將訪問元素放到隊(duì)列尾,put操作后則會(huì)調(diào)用trimToSize維護(hù)LinkedHashMap的大小不大于maxSize。
以上所述是小編給大家介紹的Android緩存機(jī)制LruCache詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Android智能指針輕量級(jí)Light Pointer初識(shí)
這篇文章主要為大家介紹了Android智能指針輕量級(jí)Light Pointer初識(shí)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
Android利用廣播接收器實(shí)現(xiàn)自動(dòng)填充短信驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了Android利用廣播接收器實(shí)現(xiàn)自動(dòng)填充短信驗(yàn)證碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
Android編程之SMS讀取短信并保存到SQLite的方法
這篇文章主要介紹了Android編程之SMS讀取短信并保存到SQLite的方法,涉及Android針對(duì)SMS短信及SQLite數(shù)據(jù)庫(kù)的相關(guān)操作技巧,需要的朋友可以參考下2015-11-11
基于Android 監(jiān)聽ContentProvider 中數(shù)據(jù)變化的相關(guān)介紹
本篇文章小編為大家介紹,基于Android 監(jiān)聽ContentProvider 中數(shù)據(jù)變化的相關(guān)介紹。需要的朋友參考下2013-04-04
ComposeDesktop開發(fā)桌面端多功能APK工具
這篇文章主要為大家介紹了ComposeDesktop開發(fā)桌面端多功能APK工具實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Android自定義viewGroup實(shí)現(xiàn)點(diǎn)擊動(dòng)畫效果
這篇文章主要介紹了Android自定義viewGroup實(shí)現(xiàn)點(diǎn)擊動(dòng)畫效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
android實(shí)現(xiàn)raw文件夾導(dǎo)入數(shù)據(jù)庫(kù)代碼
這篇文章主要介紹了android實(shí)現(xiàn)raw文件夾導(dǎo)入數(shù)據(jù)庫(kù)代碼,有需要的朋友可以參考一下2013-12-12
簡(jiǎn)單實(shí)現(xiàn)Android鬧鐘程序 附源碼
這篇文章主要幫助大家簡(jiǎn)單實(shí)現(xiàn)Android鬧鐘程序,附源碼下載,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-07-07
Android WebView或手機(jī)瀏覽器打開連接問題解決辦法總結(jié)
這篇文章主要介紹了Android WebView或手機(jī)瀏覽器打開連接問題解決辦法總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-03-03

