自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Caffeine源碼解讀-緩存過期淘汰相關(guān)算法

存儲 算法
這一篇繼續(xù)通過示例講解緩存過期相關(guān)算法部分,來看看它與guava cache有什么不一樣的設(shè)計。

[[410588]]

本文轉(zhuǎn)載自微信公眾號「肌肉碼農(nóng)」,作者鄒學(xué)。轉(zhuǎn)載本文請聯(lián)系肌肉碼農(nóng)公眾號。

引子:

上一篇通過使用示例講解了Caffeine的框架部分 Caffeine源碼解讀-架構(gòu)篇,這一篇繼續(xù)通過示例講解緩存過期相關(guān)算法部分,來看看它與guava cache有什么不一樣的設(shè)計。

使用示例:

繼續(xù)使用相同的例子,不過是從PUT、GET開始說起,了解了它的工作流程自然會知道它的緩存過期邏輯:

  1. //初始化         
  2. Cache<String, String> cache = Caffeine.newBuilder().maximumSize(100) 
  3.   .expireAfterWrite(1, TimeUnit.SECONDS).build(); 
  4. //PUT        
  5. cache.put("a""b"); 
  6. //GET 
  7.  System.out.println(cache.getIfPresent("a")); 

guava是在put時候進(jìn)行過期淘汰,那Caffeine也會是一樣嗎?

put/get:

大部分情況創(chuàng)建的是有界cache,put方法會進(jìn)入BoundedLocalCache的這個方法中:put(K key, V value, boolean notifyWriter, boolean onlyIfAbsent),當(dāng)Cache之前不包含該元素時會執(zhí)行以下的代碼:

  1. //從cache中取出之前的值  
  2. Node<K, V> prior = data.get(nodeFactory.newLookupKey(key)); 
  3. if (prior == null) { 
  4.   //prior =null 表示之前元素不存在 
  5.   //因為不存在該元素,所以需要根據(jù)key、value創(chuàng)建一個新的node 
  6.   //這里有null的判斷是這部分邏輯外層是個循環(huán),用循環(huán)的原因是后面的異步操作需要保證成功。 
  7.   if (node == null) { 
  8.     //新建node 
  9.     node = nodeFactory.newNode(key, keyReferenceQueue(), 
  10.         value, valueReferenceQueue(), newWeight, now); 
  11.     //設(shè)置Node的初始時間,用于過期策略 
  12.     setVariableTime(node, expireAfterCreate(key, value, now)); 
  13.     setAccessTime(node, now); 
  14.     setWriteTime(node, now); 
  15.   } 
  16.   if (notifyWriter && hasWriter()) { 
  17.    ............................ 
  18.   } else { //如果還未完成該key的寫 
  19.       //將新建的node寫入到data中 
  20.     prior = data.putIfAbsent(node.getKeyReference(), node); 
  21.     if (prior == null) { 
  22.       //當(dāng)之前不存在該值時,執(zhí)行afterWrite操作,并執(zhí)行AddTask任務(wù) 
  23.       afterWrite(new AddTask(node, newWeight)); 
  24.       return null
  25.     } 
  26.   } 

因為它的保持一致性代碼比較多,所以只需先讀中文注釋部分,從代碼可以看出寫緩存操作還是比較簡單:new一個node然后寫到data中去,最后觸發(fā)afterWrite后返回null.

最后一步afterWrite方法做了什么?

首先看一下AddTask是什么?

  1. final class AddTask implements Runnable { 
  2.     final Node<K, V> node; 
  3.     final int weight; 
  4.  
  5.     AddTask(Node<K, V> node, int weight) { 
  6.       this.weight = weight; 
  7.       this.node = node; 
  8.     } 
  9. ................................. 

AddTask實現(xiàn)了runnable接口,也就是說完成add操作后,會異步執(zhí)行一個add任務(wù),這個就是它與guava最大的不同點-異步, 我們先把同步部分看完,畢竟它還是put操作返回null前要執(zhí)行這部分的,afterWrite方法如下:

  1. void afterWrite(Runnable task) { 
  2. if (buffersWrites()) { 
  3.   for (int i = 0; i < WRITE_BUFFER_RETRIES; i++) { 
  4.     if (writeBuffer().offer(task)) { 
  5.       //觸發(fā)寫后調(diào)度 
  6.       scheduleAfterWrite(); 
  7.       return
  8.     } 
  9.     scheduleDrainBuffers(); 
  10.   } 
  11.   .......... 
  12. else { 
  13.   scheduleAfterWrite(); 

從上面代碼來看,該方法觸發(fā)了寫后調(diào)度,寫后調(diào)度最終后異步執(zhí)行drainBuffersTask,這個任務(wù)會整理cache中各node狀態(tài)并做出處理:

  1. voidscheduleDrainBuffers() { 
  2.   if (drainStatus() >= PROCESSING_TO_IDLE) { 
  3.     return
  4.   } 
  5.   if (evictionLock.tryLock()) { 
  6.     try { 
  7.       //獲得狀態(tài) 
  8.       int drainStatus = drainStatus(); 
  9.       //只允許存在三種狀態(tài) 
  10.       if (drainStatus >= PROCESSING_TO_IDLE) { 
  11.         return
  12.       } 
  13.       lazySetDrainStatus(PROCESSING_TO_IDLE); 
  14.       //異步調(diào)用內(nèi)存調(diào)整任務(wù) drainBuffersTask 
  15.       executor().execute(drainBuffersTask); 
  16.     } catch (Throwable t) { 
  17.       logger.log(Level.WARNING, "Exception thrown when submitting maintenance task", t); 
  18.       maintenance(/* ignored */ null); 
  19.     } finally { 
  20.       evictionLock.unlock(); 
  21.     } 
  22.   } 

從上面步驟來看,put流程是這樣的:先將元素寫入到cache,然后觸發(fā)調(diào)度,調(diào)度會根據(jù)閑忙狀態(tài)判斷是否執(zhí)行異步drainBuffersTask。

get的流程與put之差不多,因為get會改變key的使用情況影響過期結(jié)果,所以最終也可能會觸發(fā)drainBuffersTask執(zhí)行maintenance方法來清理緩存:

  1. void maintenance(@Nullable Runnable task) { 
  2.   lazySetDrainStatus(PROCESSING_TO_IDLE); 
  3.  
  4.   try { 
  5.     //排出讀緩存 
  6.     drainReadBuffer(); 
  7.   //排出寫緩存 
  8.     drainWriteBuffer(); 
  9.     if (task != null) { 
  10.       task.run(); 
  11.     } 
  12.    
  13.     //排出key引用 
  14.     drainKeyReferences(); 
  15.     //排出value引用 
  16.     drainValueReferences(); 
  17.     //過期entry 
  18.     expireEntries(); 
  19.     //淘汰entry 
  20.     evictEntries(); 
  21.   } finally { 
  22.     if ((drainStatus() != PROCESSING_TO_IDLE) || !casDrainStatus(PROCESSING_TO_IDLE, IDLE)) { 
  23.       lazySetDrainStatus(REQUIRED); 
  24.     } 
  25.   } 

數(shù)據(jù)結(jié)構(gòu)

上一篇文章有講到Caffeine使用一個ConcurrencyHashMap來保存所有數(shù)據(jù),而這一節(jié)主要講過期淘汰策略所采用的數(shù)據(jù)結(jié)構(gòu),其中寫過期是使用writeOrderDeque,這個比較簡單無需多說,而讀過期相對復(fù)雜很多,使用W-TinyLFU的結(jié)構(gòu)與算法。

網(wǎng)絡(luò)上有很多文章介紹W-TinyLFU結(jié)構(gòu)的,大家可以去查一下,這里主要是從源碼來分析,總的來說它使用了三個雙端隊列:accessOrderEdenDeque,accessOrderProbationDeque,accessOrderProtectedDeque,使用雙端隊列的原因是支持LRU算法比較方便。

accessOrderEdenDeque屬于eden區(qū),緩存1%的數(shù)據(jù),其余的99%緩存在main區(qū)。

accessOrderProbationDeque屬于main區(qū),緩存main內(nèi)數(shù)據(jù)的20%,這部分是屬于冷數(shù)據(jù),即將補淘汰。

accessOrderProtectedDeque屬于main區(qū),緩存main內(nèi)數(shù)據(jù)的20%,這部分是屬于熱數(shù)據(jù),是整個緩存的主存區(qū)。

我們先看一下淘汰方法入口:

  1. void evictEntries() { 
  2.   if (!evicts()) { 
  3.     return
  4.   } 
  5.   //先從edn區(qū)淘汰 
  6.   int candidates = evictFromEden(); 
  7.   //eden淘汰后的數(shù)據(jù)進(jìn)入main區(qū),然后再從main區(qū)淘汰 
  8.   evictFromMain(candidates); 

accessOrderEdenDeque對應(yīng)W-TinyLFU的W(window),這里保存的是最新寫入數(shù)據(jù)的引用,它使用LRU淘汰,這里面的數(shù)據(jù)主要是應(yīng)對突發(fā)流量的問題,淘汰后的數(shù)據(jù)進(jìn)入accessOrderProbationDeque.代碼如下:

  1. int evictFromEden() { 
  2.   int candidates = 0; 
  3.   Node<K, V> node = accessOrderEdenDeque().peek(); 
  4.   while (edenWeightedSize() > edenMaximum()) { 
  5.     // The pending operations will adjust the size to reflect the correct weight 
  6.     if (node == null) { 
  7.       break; 
  8.     } 
  9.  
  10.     Node<K, V> next = node.getNextInAccessOrder(); 
  11.     if (node.getWeight() != 0) { 
  12.       node.makeMainProbation(); 
  13.       //先從eden區(qū)移除 
  14.       accessOrderEdenDeque().remove(node); 
  15.       //移除的數(shù)據(jù)加入到main區(qū)的probation隊列 
  16.       accessOrderProbationDeque().add(node); 
  17.       candidates++; 
  18.  
  19.       lazySetEdenWeightedSize(edenWeightedSize() - node.getPolicyWeight()); 
  20.     } 
  21.     node = next
  22.   } 
  23.  
  24.   return candidates; 

數(shù)據(jù)進(jìn)入probation隊列后,繼續(xù)執(zhí)行以下代碼:

  1. void evictFromMain(int candidates) { 
  2.   int victimQueue = PROBATION; 
  3.   Node<K, V> victim = accessOrderProbationDeque().peekFirst(); 
  4.   Node<K, V> candidate = accessOrderProbationDeque().peekLast(); 
  5.   while (weightedSize() > maximum()) { 
  6.     // Stop trying to evict candidates and always prefer the victim 
  7.     if (candidates == 0) { 
  8.       candidate = null
  9.     } 
  10.  
  11.     // Try evicting from the protected and eden queues 
  12.     if ((candidate == null) && (victim == null)) { 
  13.       if (victimQueue == PROBATION) { 
  14.         victim = accessOrderProtectedDeque().peekFirst(); 
  15.         victimQueue = PROTECTED; 
  16.         continue
  17.       } else if (victimQueue == PROTECTED) { 
  18.         victim = accessOrderEdenDeque().peekFirst(); 
  19.         victimQueue = EDEN; 
  20.         continue
  21.       } 
  22.  
  23.       // The pending operations will adjust the size to reflect the correct weight 
  24.       break; 
  25.     } 
  26.  
  27.     // Skip over entries with zero weight 
  28.     if ((victim != null) && (victim.getPolicyWeight() == 0)) { 
  29.       victim = victim.getNextInAccessOrder(); 
  30.       continue
  31.     } else if ((candidate != null) && (candidate.getPolicyWeight() == 0)) { 
  32.       candidate = candidate.getPreviousInAccessOrder(); 
  33.       candidates--; 
  34.       continue
  35.     } 
  36.  
  37.     // Evict immediately if only one of the entries is present 
  38.     if (victim == null) { 
  39.       candidates--; 
  40.       Node<K, V> evict = candidate; 
  41.       candidate = candidate.getPreviousInAccessOrder(); 
  42.       evictEntry(evict, RemovalCause.SIZE, 0L); 
  43.       continue
  44.     } else if (candidate == null) { 
  45.       Node<K, V> evict = victim; 
  46.       victim = victim.getNextInAccessOrder(); 
  47.       evictEntry(evict, RemovalCause.SIZE, 0L); 
  48.       continue
  49.     } 
  50.  
  51.     // Evict immediately if an entry was collected 
  52.     K victimKey = victim.getKey(); 
  53.     K candidateKey = candidate.getKey(); 
  54.     if (victimKey == null) { 
  55.       Node<K, V> evict = victim; 
  56.       victim = victim.getNextInAccessOrder(); 
  57.       evictEntry(evict, RemovalCause.COLLECTED, 0L); 
  58.       continue
  59.     } else if (candidateKey == null) { 
  60.       candidates--; 
  61.       Node<K, V> evict = candidate; 
  62.       candidate = candidate.getPreviousInAccessOrder(); 
  63.       evictEntry(evict, RemovalCause.COLLECTED, 0L); 
  64.       continue
  65.     } 
  66.  
  67.     // Evict immediately if the candidate's weight exceeds the maximum 
  68.     if (candidate.getPolicyWeight() > maximum()) { 
  69.       candidates--; 
  70.       Node<K, V> evict = candidate; 
  71.       candidate = candidate.getPreviousInAccessOrder(); 
  72.       evictEntry(evict, RemovalCause.SIZE, 0L); 
  73.       continue
  74.     } 
  75.  
  76.     // Evict the entry with the lowest frequency 
  77.     candidates--; 
  78.     //最核心算法在這里:從probation的頭尾取出兩個node進(jìn)行比較頻率,頻率更小者將被remove 
  79.     if (admit(candidateKey, victimKey)) { 
  80.       Node<K, V> evict = victim; 
  81.       victim = victim.getNextInAccessOrder(); 
  82.       evictEntry(evict, RemovalCause.SIZE, 0L); 
  83.       candidate = candidate.getPreviousInAccessOrder(); 
  84.     } else { 
  85.       Node<K, V> evict = candidate; 
  86.       candidate = candidate.getPreviousInAccessOrder(); 
  87.       evictEntry(evict, RemovalCause.SIZE, 0L); 
  88.     } 
  89.   } 

上面的代碼邏輯是從probation的頭尾取出兩個node進(jìn)行比較頻率,頻率更小者將被remove,其中尾部元素就是上一部分從eden中淘汰出來的元素,如果將兩步邏輯合并起來講是這樣的:在eden隊列通過lru淘汰出來的”候選者“與probation隊列通過lru淘汰出來的“被驅(qū)逐者“進(jìn)行頻率比較,失敗者將被從cache中真正移除。下面看一下它的比較邏輯admit:

  1. boolean admit(K candidateKey, K victimKey) { 
  2.   int victimFreq = frequencySketch().frequency(victimKey); 
  3.   int candidateFreq = frequencySketch().frequency(candidateKey); 
  4.   //如果候選者的頻率高就淘汰被驅(qū)逐者 
  5.   if (candidateFreq > victimFreq) { 
  6.     return true
  7.     //如果被驅(qū)逐者比候選者的頻率高,并且候選者頻率小于等于5則淘汰者 
  8.   } else if (candidateFreq <= 5) { 
  9.     // The maximum frequency is 15 and halved to 7 after a reset to age the history. An attack 
  10.     // exploits that a hot candidate is rejected in favor of a hot victim. The threshold of a warm 
  11.     // candidate reduces the number of random acceptances to minimize the impact on the hit rate. 
  12.     return false
  13.   } 
  14.   //隨機(jī)淘汰 
  15.   int random = ThreadLocalRandom.current().nextInt(); 
  16.   return ((random & 127) == 0); 

從frequencySketch取出候選者與被驅(qū)逐者的頻率,如果候選者的頻率高就淘汰被驅(qū)逐者,如果被驅(qū)逐者比候選者的頻率高,并且候選者頻率小于等于5則淘汰者,如果前面兩個條件都不滿足則隨機(jī)淘汰。

整個過程中你是不是發(fā)現(xiàn)protectedDeque并沒有什么作用,那它是怎么作為主存區(qū)來保存大部分?jǐn)?shù)據(jù)的呢?

  1. //onAccess方法觸發(fā)該方法  
  2. void reorderProbation(Node<K, V> node) { 
  3.   if (!accessOrderProbationDeque().contains(node)) { 
  4.     // Ignore stale accesses for an entry that is no longer present 
  5.     return
  6.   } else if (node.getPolicyWeight() > mainProtectedMaximum()) { 
  7.     return
  8.   } 
  9.  
  10.   long mainProtectedWeightedSize = mainProtectedWeightedSize() + node.getPolicyWeight(); 
  11.  //先從probation中移除 
  12.  accessOrderProbationDeque().remove(node); 
  13. //加入到protected中 
  14.   accessOrderProtectedDeque().add(node); 
  15.   node.makeMainProtected(); 
  16.  
  17.   long mainProtectedMaximum = mainProtectedMaximum(); 
  18. //從protected中移除 
  19.   while (mainProtectedWeightedSize > mainProtectedMaximum) { 
  20.     Node<K, V> demoted = accessOrderProtectedDeque().pollFirst(); 
  21.     if (demoted == null) { 
  22.       break; 
  23.     } 
  24.     demoted.makeMainProbation(); 
  25.     //加入到probation中 
  26.     accessOrderProbationDeque().add(demoted); 
  27.     mainProtectedWeightedSize -= node.getPolicyWeight(); 
  28.   } 
  29.  
  30.   lazySetMainProtectedWeightedSize(mainProtectedWeightedSize); 

當(dāng)數(shù)據(jù)被訪問時并且該數(shù)據(jù)在probation中,這個數(shù)據(jù)就會移動到protected中去,同時通過lru從protected中淘汰一個數(shù)據(jù)進(jìn)入到probation中。

這樣數(shù)據(jù)流轉(zhuǎn)的邏輯全部通了:新數(shù)據(jù)都會進(jìn)入到eden中,通過lru淘汰到probation,并與probation中通過lru淘汰的數(shù)據(jù)進(jìn)行使用頻率pk,如果勝利了就繼續(xù)留在probation中,如果失敗了就會被直接淘汰,當(dāng)這條數(shù)據(jù)被訪問了,則移動到protected。當(dāng)其它數(shù)據(jù)被訪問了,則它可能會從protected中通過lru淘汰到probation中。

TinyLFU

傳統(tǒng)LFU一般使用key-value形式來記錄每個key的頻率,優(yōu)點是數(shù)據(jù)結(jié)構(gòu)非常簡單,并且能跟緩存本身的數(shù)據(jù)結(jié)構(gòu)復(fù)用,增加一個屬性記錄頻率就行了,它的缺點也比較明顯就是頻率這個屬性會占用很大的空間,但如果改用壓縮方式存儲頻率呢? 頻率占用空間肯定可以減少,但會引出另外一個問題:怎么從壓縮后的數(shù)據(jù)里獲得對應(yīng)key的頻率呢?

TinyLFU的解決方案是類似位圖的方法,將key取hash值獲得它的位下標(biāo),然后用這個下標(biāo)來找頻率,但位圖只有0、1兩個值,那頻率明顯可能會非常大,這要怎么處理呢? 另外使用位圖需要預(yù)占非常大的空間,這個問題怎么解決呢?

TinyLFU根據(jù)最大數(shù)據(jù)量設(shè)置生成一個long數(shù)組,然后將頻率值保存在其中的四個long的4個bit位中(4個bit位不會大于15),取頻率值時則取四個中的最小一個。

Caffeine認(rèn)為頻率大于15已經(jīng)很高了,是屬于熱數(shù)據(jù),所以它只需要4個bit位來保存,long有8個字節(jié)64位,這樣可以保存16個頻率。取hash值的后左移兩位,然后加上hash四次,這樣可以利用到16個中的13個,利用率挺高的,或許有更好的算法能將16個都利用到。

  1. public void increment(@Nonnull E e) { 
  2.     if (isNotInitialized()) { 
  3.       return
  4.     } 
  5.  
  6.     int hash = spread(e.hashCode()); 
  7.     int start = (hash & 3) << 2; 
  8.  
  9.     // Loop unrolling improves throughput by 5m ops/s 
  10.     int index0 = indexOf(hash, 0); //indexOf也是一種hash方法,不過會通過tableMask來限制范圍 
  11.     int index1 = indexOf(hash, 1); 
  12.     int index2 = indexOf(hash, 2); 
  13.     int index3 = indexOf(hash, 3); 
  14.  
  15.     boolean added = incrementAt(index0, start); 
  16.     added |= incrementAt(index1, start + 1); 
  17.     added |= incrementAt(index2, start + 2); 
  18.     added |= incrementAt(index3, start + 3); 
  19.  
  20.     //當(dāng)數(shù)據(jù)寫入次數(shù)達(dá)到數(shù)據(jù)長度時就重置 
  21.     if (added && (++size == sampleSize)) { 
  22.       reset(); 
  23.     } 
  24.   } 

給對應(yīng)位置的bit位四位的Int值加1:

  1. boolean incrementAt(int i, int j) { 
  2.   int offset = j << 2; 
  3.   long mask = (0xfL << offset); 
  4.   //當(dāng)已達(dá)到15時,次數(shù)不再增加 
  5.   if ((table[i] & mask) != mask) { 
  6.     table[i] += (1L << offset); 
  7.     return true
  8.   } 
  9.   return false

獲得值的方法也是通過四次hash來獲得,然后取最小值:

  1. public int frequency(@Nonnull E e) { 
  2.   if (isNotInitialized()) { 
  3.     return 0; 
  4.   } 
  5.  
  6.   int hash = spread(e.hashCode()); 
  7.   int start = (hash & 3) << 2; 
  8.   int frequency = Integer.MAX_VALUE; 
  9.   //四次hash 
  10.   for (int i = 0; i < 4; i++) { 
  11.     int index = indexOf(hash, i); 
  12.     //獲得bit位四位的Int值 
  13.     int count = (int) ((table[index] >>> ((start + i) << 2)) & 0xfL); 
  14.     //取最小值 
  15.     frequency = Math.min(frequency, count); 
  16.   } 
  17.   return frequency; 

當(dāng)數(shù)據(jù)寫入次數(shù)達(dá)到數(shù)據(jù)長度時就會將次數(shù)減半,一些冷數(shù)據(jù)在這個過程中將歸0,這樣會使hash沖突降低:

  1. void reset() { 
  2.   int count = 0; 
  3.   for (int i = 0; i < table.length; i++) { 
  4.     count += Long.bitCount(table[i] & ONE_MASK); 
  5.     table[i] = (table[i] >>> 1) & RESET_MASK; 
  6.   } 
  7.   size = (size >>> 1) - (count >>> 2); 

 

責(zé)任編輯:武曉燕 來源: 肌肉碼農(nóng)
相關(guān)推薦

2021-11-08 11:21:18

redis 淘汰算法

2020-02-19 19:18:02

緩存查詢速度淘汰算法

2021-11-04 08:04:49

緩存CaffeineSpringBoot

2021-07-12 22:50:29

Caffeine數(shù)據(jù)結(jié)構(gòu)

2024-12-06 10:02:46

2024-07-25 14:04:16

2025-03-26 03:25:00

SpringGuavaCaffeine

2023-10-26 07:13:14

Redis內(nèi)存淘汰

2012-02-03 11:31:33

HibernateJava

2024-09-26 06:30:36

2018-07-05 16:15:26

緩存數(shù)據(jù)cache miss

2022-03-31 13:58:37

分布式SpringRedis

2021-03-01 18:42:02

緩存LRU算法

2012-12-17 14:54:55

算法緩存Java

2021-09-10 18:47:22

Redis淘汰策略

2024-12-03 14:38:07

CaffeineRedis二級緩存

2021-01-19 10:39:03

Redis緩存數(shù)據(jù)

2020-05-12 10:00:14

緩存算法贈源碼

2019-03-20 08:00:00

DNS緩存欺騙惡意軟件

2009-12-28 15:00:21

ADO操作
點贊
收藏

51CTO技術(shù)棧公眾號