Caffeine源码解读-缓存过期淘汰相关算法

存储 算法
这一篇继续通过示例讲解缓存过期相关算法部分,来看看它与guava cache有什么不一样的设计。

[[410588]]

本文转载自微信公众号「肌肉码农」,作者邹学。转载本文请联系肌肉码农公众号。

引子:

上一篇通过使用示例讲解了Caffeine的框架部分 Caffeine源码解读-架构篇,这一篇继续通过示例讲解缓存过期相关算法部分,来看看它与guava cache有什么不一样的设计。

使用示例:

继续使用相同的例子,不过是从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时候进行过期淘汰,那Caffeine也会是一样吗?

put/get:

大部分情况创建的是有界cache,put方法会进入BoundedLocalCache的这个方法中:put(K key, V value, boolean notifyWriter, boolean onlyIfAbsent),当Cache之前不包含该元素时会执行以下的代码:

  1. //从cache中取出之前的值  
  2. Node<K, V> prior = data.get(nodeFactory.newLookupKey(key)); 
  3. if (prior == null) { 
  4.   //prior =null 表示之前元素不存在 
  5.   //因为不存在该元素,所以需要根据key、value创建一个新的node 
  6.   //这里有null的判断是这部分逻辑外层是个循环,用循环的原因是后面的异步操作需要保证成功。 
  7.   if (node == null) { 
  8.     //新建node 
  9.     node = nodeFactory.newNode(key, keyReferenceQueue(), 
  10.         value, valueReferenceQueue(), newWeight, now); 
  11.     //设置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.       //当之前不存在该值时,执行afterWrite操作,并执行AddTask任务 
  23.       afterWrite(new AddTask(node, newWeight)); 
  24.       return null
  25.     } 
  26.   } 

因为它的保持一致性代码比较多,所以只需先读中文注释部分,从代码可以看出写缓存操作还是比较简单:new一个node然后写到data中去,最后触发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实现了runnable接口,也就是说完成add操作后,会异步执行一个add任务,这个就是它与guava最大的不同点-异步, 我们先把同步部分看完,毕竟它还是put操作返回null前要执行这部分的,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.       //触发写后调度 
  6.       scheduleAfterWrite(); 
  7.       return
  8.     } 
  9.     scheduleDrainBuffers(); 
  10.   } 
  11.   .......... 
  12. else { 
  13.   scheduleAfterWrite(); 

从上面代码来看,该方法触发了写后调度,写后调度最终后异步执行drainBuffersTask,这个任务会整理cache中各node状态并做出处理:

  1. voidscheduleDrainBuffers() { 
  2.   if (drainStatus() >= PROCESSING_TO_IDLE) { 
  3.     return
  4.   } 
  5.   if (evictionLock.tryLock()) { 
  6.     try { 
  7.       //获得状态 
  8.       int drainStatus = drainStatus(); 
  9.       //只允许存在三种状态 
  10.       if (drainStatus >= PROCESSING_TO_IDLE) { 
  11.         return
  12.       } 
  13.       lazySetDrainStatus(PROCESSING_TO_IDLE); 
  14.       //异步调用内存调整任务 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,然后触发调度,调度会根据闲忙状态判断是否执行异步drainBuffersTask。

get的流程与put之差不多,因为get会改变key的使用情况影响过期结果,所以最终也可能会触发drainBuffersTask执行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.   } 

数据结构

上一篇文章有讲到Caffeine使用一个ConcurrencyHashMap来保存所有数据,而这一节主要讲过期淘汰策略所采用的数据结构,其中写过期是使用writeOrderDeque,这个比较简单无需多说,而读过期相对复杂很多,使用W-TinyLFU的结构与算法。

网络上有很多文章介绍W-TinyLFU结构的,大家可以去查一下,这里主要是从源码来分析,总的来说它使用了三个双端队列:accessOrderEdenDeque,accessOrderProbationDeque,accessOrderProtectedDeque,使用双端队列的原因是支持LRU算法比较方便。

accessOrderEdenDeque属于eden区,缓存1%的数据,其余的99%缓存在main区。

accessOrderProbationDeque属于main区,缓存main内数据的20%,这部分是属于冷数据,即将补淘汰。

accessOrderProtectedDeque属于main区,缓存main内数据的20%,这部分是属于热数据,是整个缓存的主存区。

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

  1. void evictEntries() { 
  2.   if (!evicts()) { 
  3.     return
  4.   } 
  5.   //先从edn区淘汰 
  6.   int candidates = evictFromEden(); 
  7.   //eden淘汰后的数据进入main区,然后再从main区淘汰 
  8.   evictFromMain(candidates); 

accessOrderEdenDeque对应W-TinyLFU的W(window),这里保存的是最新写入数据的引用,它使用LRU淘汰,这里面的数据主要是应对突发流量的问题,淘汰后的数据进入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区移除 
  14.       accessOrderEdenDeque().remove(node); 
  15.       //移除的数据加入到main区的probation队列 
  16.       accessOrderProbationDeque().add(node); 
  17.       candidates++; 
  18.  
  19.       lazySetEdenWeightedSize(edenWeightedSize() - node.getPolicyWeight()); 
  20.     } 
  21.     node = next
  22.   } 
  23.  
  24.   return candidates; 

数据进入probation队列后,继续执行以下代码:

  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进行比较频率,频率更小者将被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进行比较频率,频率更小者将被remove,其中尾部元素就是上一部分从eden中淘汰出来的元素,如果将两步逻辑合并起来讲是这样的:在eden队列通过lru淘汰出来的”候选者“与probation队列通过lru淘汰出来的“被驱逐者“进行频率比较,失败者将被从cache中真正移除。下面看一下它的比较逻辑admit:

  1. boolean admit(K candidateKey, K victimKey) { 
  2.   int victimFreq = frequencySketch().frequency(victimKey); 
  3.   int candidateFreq = frequencySketch().frequency(candidateKey); 
  4.   //如果候选者的频率高就淘汰被驱逐者 
  5.   if (candidateFreq > victimFreq) { 
  6.     return true
  7.     //如果被驱逐者比候选者的频率高,并且候选者频率小于等于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.   //随机淘汰 
  15.   int random = ThreadLocalRandom.current().nextInt(); 
  16.   return ((random & 127) == 0); 

从frequencySketch取出候选者与被驱逐者的频率,如果候选者的频率高就淘汰被驱逐者,如果被驱逐者比候选者的频率高,并且候选者频率小于等于5则淘汰者,如果前面两个条件都不满足则随机淘汰。

整个过程中你是不是发现protectedDeque并没有什么作用,那它是怎么作为主存区来保存大部分数据的呢?

  1. //onAccess方法触发该方法  
  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); 

当数据被访问时并且该数据在probation中,这个数据就会移动到protected中去,同时通过lru从protected中淘汰一个数据进入到probation中。

这样数据流转的逻辑全部通了:新数据都会进入到eden中,通过lru淘汰到probation,并与probation中通过lru淘汰的数据进行使用频率pk,如果胜利了就继续留在probation中,如果失败了就会被直接淘汰,当这条数据被访问了,则移动到protected。当其它数据被访问了,则它可能会从protected中通过lru淘汰到probation中。

TinyLFU

传统LFU一般使用key-value形式来记录每个key的频率,优点是数据结构非常简单,并且能跟缓存本身的数据结构复用,增加一个属性记录频率就行了,它的缺点也比较明显就是频率这个属性会占用很大的空间,但如果改用压缩方式存储频率呢? 频率占用空间肯定可以减少,但会引出另外一个问题:怎么从压缩后的数据里获得对应key的频率呢?

TinyLFU的解决方案是类似位图的方法,将key取hash值获得它的位下标,然后用这个下标来找频率,但位图只有0、1两个值,那频率明显可能会非常大,这要怎么处理呢? 另外使用位图需要预占非常大的空间,这个问题怎么解决呢?

TinyLFU根据最大数据量设置生成一个long数组,然后将频率值保存在其中的四个long的4个bit位中(4个bit位不会大于15),取频率值时则取四个中的最小一个。

Caffeine认为频率大于15已经很高了,是属于热数据,所以它只需要4个bit位来保存,long有8个字节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.     //当数据写入次数达到数据长度时就重置 
  21.     if (added && (++size == sampleSize)) { 
  22.       reset(); 
  23.     } 
  24.   } 

给对应位置的bit位四位的Int值加1:

  1. boolean incrementAt(int i, int j) { 
  2.   int offset = j << 2; 
  3.   long mask = (0xfL << offset); 
  4.   //当已达到15时,次数不再增加 
  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; 

当数据写入次数达到数据长度时就会将次数减半,一些冷数据在这个过程中将归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); 

 

责任编辑:武晓燕 来源: 肌肉码农
相关推荐

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数据结构

2023-10-26 07:13:14

Redis内存淘汰

2018-07-05 16:15:26

缓存数据cache miss

2012-02-03 11:31:33

HibernateJava

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淘汰策略

2021-01-19 10:39:03

Redis缓存数据

2020-05-12 10:00:14

缓存算法赠源码

2019-03-20 08:00:00

DNS缓存欺骗恶意软件

2010-01-04 14:54:08

ADO参数

2009-12-28 15:00:21

ADO操作

2016-08-29 19:12:52

JavascriptBackbone前端

2010-01-27 10:37:17

Android图片浏览

2015-06-15 10:32:44

Java核心源码解读

2022-07-01 14:20:49

Redis策略函数
点赞
收藏

51CTO技术栈公众号