searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

Caffeine缓存设计分析

2023-12-22 10:22:49
7
0

前言

        Caffeine是Java缓存框架,在springboot 2.0 中替代大名鼎鼎的Guava cache 正式成为默认缓存实现。在大量缓存情况下,其命中率和并发性能,其他本地缓存实现。我们下载其源码后通过跑jmh测试下其读写性能

    jmh -PincludePattern=GetPutBenchmark

下面是测试结果,caffeine性能均优于其他实现。

Benchmark                                            (cacheType)   Mode  Cnt         Score          Error  Units
GetPutBenchmark.read_only                      LinkedHashMap_Lru  thrpt    3   9657567.978 ��  1393379.492  ops/s
GetPutBenchmark.read_only                               Caffeine  thrpt    3  70930177.345 �� 23803773.390  ops/s
GetPutBenchmark.read_only                ConcurrentLinkedHashMap  thrpt    3  30758281.141 �� 16813685.927  ops/s
GetPutBenchmark.read_only                       Coherence_Hybrid  thrpt    3  29541933.801 ��  1160841.941  ops/s
GetPutBenchmark.read_only                               Ehcache3  thrpt    3  70204972.204 ��  2985687.988  ops/s
GetPutBenchmark.read_only                                  Guava  thrpt    3  20585147.285 ��   931015.649  ops/s
GetPutBenchmark.readwrite                      LinkedHashMap_Lru  thrpt    3  10744129.426 ��   679063.411  ops/s
GetPutBenchmark.readwrite:readwrite_get        LinkedHashMap_Lru  thrpt    3   7515865.965 ��  1619483.799  ops/s
GetPutBenchmark.readwrite:readwrite_put        LinkedHashMap_Lru  thrpt    3   3228263.461 ��  1888412.642  ops/s
GetPutBenchmark.readwrite                               Caffeine  thrpt    3  67726271.399 �� 10564510.105  ops/s
GetPutBenchmark.readwrite:readwrite_get                 Caffeine  thrpt    3  59832526.734 ��  8503760.578  ops/s
GetPutBenchmark.readwrite:readwrite_put                 Caffeine  thrpt    3   7893744.665 ��  2682583.353  ops/s
GetPutBenchmark.readwrite                ConcurrentLinkedHashMap  thrpt    3  30472483.321 ��  5443261.221  ops/s
GetPutBenchmark.readwrite:readwrite_get  ConcurrentLinkedHashMap  thrpt    3  25862663.407 ��  7180846.734  ops/s
GetPutBenchmark.readwrite:readwrite_put  ConcurrentLinkedHashMap  thrpt    3   4609819.914 ��  2437033.702  ops/s
GetPutBenchmark.readwrite                       Coherence_Hybrid  thrpt    3  27352236.688 ��  2054858.487  ops/s
GetPutBenchmark.readwrite:readwrite_get         Coherence_Hybrid  thrpt    3  24477302.453 ��  1914848.604  ops/s
GetPutBenchmark.readwrite:readwrite_put         Coherence_Hybrid  thrpt    3   2874934.236 ��  1203791.003  ops/s
GetPutBenchmark.readwrite                               Ehcache3  thrpt    3  48735270.246 ��  2648040.014  ops/s
GetPutBenchmark.readwrite:readwrite_get                 Ehcache3  thrpt    3  44028929.911 ��  3239305.323  ops/s
GetPutBenchmark.readwrite:readwrite_put                 Ehcache3  thrpt    3   4706340.334 ��   726297.450  ops/s
GetPutBenchmark.readwrite                                  Guava  thrpt    3  19327134.687 ��  6330774.417  ops/s
GetPutBenchmark.readwrite:readwrite_get                    Guava  thrpt    3  18694672.970 ��  6600858.959  ops/s
GetPutBenchmark.readwrite:readwrite_put                    Guava  thrpt    3    632461.717 ��   624977.206  ops/s
GetPutBenchmark.write_only                     LinkedHashMap_Lru  thrpt    3  11242123.504 ��   295997.500  ops/s
GetPutBenchmark.write_only                              Caffeine  thrpt    3  35522090.287 �� 13561818.941  ops/s
GetPutBenchmark.write_only               ConcurrentLinkedHashMap  thrpt    3  18600282.773 �� 27731352.661  ops/s
GetPutBenchmark.write_only                      Coherence_Hybrid  thrpt    3   4552873.723 ��  7800355.132  ops/s
GetPutBenchmark.write_only                              Ehcache3  thrpt    3  17659195.512 ��  7963537.916  ops/s
GetPutBenchmark.write_only                                 Guava  thrpt    3  10129983.520 ��  1764954.824  ops/s

能有如此优秀表现,必然有一些非常值得研究的设计在里面,接下来我们一起研究下其独特的设计。

 驱逐策略

​  常见的淘汰策略有以下几种:

- Least Recently Used(LRU) - 核心是思想是最近被访问过的数据,将来被再次访问的概率大。存在热点数据的情况下,这种算法比较适合。但偶发性的、周期性批量操作容易导致数据污染。

- Least Frequently Used(LFU) - 核心是统计数据的访问频率,数据访问频率高的,将来再次被访问的概率大。这种算法需要维护所有数据的访问频次,并且每次访问时进行更新,缓存开销较大。对偶发浏览不太友好。

- FIFO 和 FILO: 队列和堆栈的思路,通常不用于缓存实现。

​  Caffeine 采用的是[Window TinyLFU](https://dl.acm.org/citation.cfm?id=3149371) (W-TinyLFU)算法,结合了LRU和LFU的优点。在统计频次方面,通过countMin sketch (一种紧凑的数据结构)解决了LFU频次统计占用空间。CountMin Sketch 采用的是Bloom Filter的设计思路。将一个key值映射做多个hash运算映射到多个bin,访问时对其所有bin进行+1操作;获取计数时只取多个bin中的最小值。通过这个matrix的运算将空间占用,计算性能和准确率控制在一个比较平衡的情况。

 

​ 利用CountMin Sketch统计识别出高频数据,并且在分段式LRU算法中作为过滤器,把高频的最近热数据识别出来。Caffeine 对频率统计在此上做了进一步的空间压缩 - 通常数字类型一般用64位long来表示,caffeine把long切分为16份每个数据进占用其中的4位。4位的最大值是15,也就是频次最大只能是15。caffeine认为这个数字范围已经能区分出数据的热度,并且在所有key的访问频次达到阈值的情况下,会对所有缓存key的频次除以2。

​  在数据保新方面,caffeine把缓存划分为俩大部分 LRU和Segmented LRU。

 

​ 新数据首先进入LRU区间,caffeine实现中叫window dequeue。在window dequeue满了的时候,lru被淘汰的数据会进入SLRU的probation dequeue。probation dequeue数据的访问频次达到一定次数时会进一步提升到 protected deque。但protected dequeue满了,降级一些数据到probation dequeue。但数据需要淘汰时,对probation dequeue的数据进行比较。probation dequeu队首部是最先进入队列的,队尾是最后加入队列的,队首和队尾的两个数据频次比较大小,小的数据被驱逐出去。

​  通过上述结构和频次自动衰减处理,caffeine节省了存储空间,同时平衡了访问频次和新鲜度俩个维度,能较好应对稀疏流量和短时超热点数据的情况。

 淘汰策略

​  Guava的读cache操作可能混杂着对过期数据的处理,对读性能影响较大。另一种做法用一个管理线程来对过期数据进行清除,但这种做法在读写的并发性上会有较大影响。

​  对缓存的并发访问被视为一个难题,因为在大多数策略中,每次访问都是对某些共享状态的写入。传统的解决方案是用一个锁来保护缓存。然后可以通过将缓存拆分为许多较小的独立区域来通过锁条带化来改进这一点,如concurrenthashmap分段式锁实现。但如果热点数据比较集中,那分段式锁依然不能达到较好的并发性能。

​  Caffeine借鉴了数据库的WAL设计思路,先写缓存再通过后台异步批量刷入缓存变更。读操作每个线程有一个单独的ring buffer存放读记录,写操作所有线程共享一个ring buffer。下面引用官方架构图:

注:图片来源 https://github.com/ben-manes/caffeine/wiki

 

时间轮过期算法

​  在处理不同过期时间的任务时,找到最早过期的任务跟当前时间比较,如果已过期则执行过期处理。问题在于如何高效的找到最早过期的任务。通常最值排序问题可以通过priority queue来解决,但priority queue 需要log(n),耗时长并且并发性能很差。数组的读写性能较好只需要O(1),可以把60秒内的任务拆解纯到60个格子中,每个格子有多个则对其进行拉链处理,类似hashmap的数组+链表结构。每次指针往前移动一格,格子内都是需要处理的数据。超过60秒范围内的数据则对其加个round属性,如70秒后表示的时 round = 1 = 70 /60, 在当前指针位置+10的地方插入。但则会引入一个新的问题,就是每次都需要对格子内的链表进行排序进行处理,如果格子内链表较长则带来的性能也较差。

因此用round来处理超范围的任务并不常用,通常是采用多层级的时间轮来处理。想象下我们的时钟,有多个指针,每个指针指向不同的轮子,并且每个轮子的粒度都不一样。当上一级任务处理完后,则从下一级更大粒度的轮子里面取出任务填充到细粒度的轮子里去。kafka、zookeeper、Linux内核均有类似实现,感兴趣的可以去了解下更多的实现细节,在此不作细述。

 

代码生成

​  为了尽量压缩缓存的内存footprint,caffeine甚至使用了代码生成工具,为每种配置策略生成了不同的数据节点node实现。在使用的时候,按需加载实例化。类的每个属性字段都是必须的,没有任何冗余字段,这样在实例化的时候内存占用最小化。

其按需加载的实现代码也是非常直白,根据不同特性如是否WeakValue拼接不同字符来拼出最终需要的类名,如下所示:

static <K, V> NodeFactory<K, V> newFactory(Caffeine<K, V> builder, boolean isAsync) {
    if (builder.interner) {
      return new Interned<>();
    }
    var className = getClassName(builder, isAsync);
    return loadFactory(className);
  }

  static String getClassName(Caffeine<?, ?> builder, boolean isAsync) {
    var className = new StringBuilder(Node.class.getPackageName()).append('.');
    if (builder.isStrongKeys()) {
      className.append('P');
    } else {
      className.append('F');
    }
    if (builder.isStrongValues()) {
      className.append('S');
    } else if (builder.isWeakValues()) {
      className.append('W');
    } else {
      className.append('D');
    }
    if (builder.expiresVariable()) {
      if (builder.refreshAfterWrite()) {
        className.append('A');
        if (builder.evicts()) {
          className.append('W');
        }
      } else {
        className.append('W');
      }
    } else {
      if (builder.expiresAfterAccess()) {
        className.append('A');
      }
      if (builder.expiresAfterWrite()) {
        className.append('W');
      }
    }
    if (builder.refreshAfterWrite()) {
      className.append('R');
    }
    if (builder.evicts()) {
      className.append('M');
      if (isAsync || (builder.isWeighted() && (builder.weigher != Weigher.singletonWeigher()))) {
        className.append('W');
      } else {
        className.append('S');
      }
    }
    return className.toString();
  }

最终按照拼接出来的名字,加载不同的node实现。

 

0条评论
作者已关闭评论
z****n
1文章数
0粉丝数
z****n
1 文章 | 0 粉丝
z****n
1文章数
0粉丝数
z****n
1 文章 | 0 粉丝
原创

Caffeine缓存设计分析

2023-12-22 10:22:49
7
0

前言

        Caffeine是Java缓存框架,在springboot 2.0 中替代大名鼎鼎的Guava cache 正式成为默认缓存实现。在大量缓存情况下,其命中率和并发性能,其他本地缓存实现。我们下载其源码后通过跑jmh测试下其读写性能

    jmh -PincludePattern=GetPutBenchmark

下面是测试结果,caffeine性能均优于其他实现。

Benchmark                                            (cacheType)   Mode  Cnt         Score          Error  Units
GetPutBenchmark.read_only                      LinkedHashMap_Lru  thrpt    3   9657567.978 ��  1393379.492  ops/s
GetPutBenchmark.read_only                               Caffeine  thrpt    3  70930177.345 �� 23803773.390  ops/s
GetPutBenchmark.read_only                ConcurrentLinkedHashMap  thrpt    3  30758281.141 �� 16813685.927  ops/s
GetPutBenchmark.read_only                       Coherence_Hybrid  thrpt    3  29541933.801 ��  1160841.941  ops/s
GetPutBenchmark.read_only                               Ehcache3  thrpt    3  70204972.204 ��  2985687.988  ops/s
GetPutBenchmark.read_only                                  Guava  thrpt    3  20585147.285 ��   931015.649  ops/s
GetPutBenchmark.readwrite                      LinkedHashMap_Lru  thrpt    3  10744129.426 ��   679063.411  ops/s
GetPutBenchmark.readwrite:readwrite_get        LinkedHashMap_Lru  thrpt    3   7515865.965 ��  1619483.799  ops/s
GetPutBenchmark.readwrite:readwrite_put        LinkedHashMap_Lru  thrpt    3   3228263.461 ��  1888412.642  ops/s
GetPutBenchmark.readwrite                               Caffeine  thrpt    3  67726271.399 �� 10564510.105  ops/s
GetPutBenchmark.readwrite:readwrite_get                 Caffeine  thrpt    3  59832526.734 ��  8503760.578  ops/s
GetPutBenchmark.readwrite:readwrite_put                 Caffeine  thrpt    3   7893744.665 ��  2682583.353  ops/s
GetPutBenchmark.readwrite                ConcurrentLinkedHashMap  thrpt    3  30472483.321 ��  5443261.221  ops/s
GetPutBenchmark.readwrite:readwrite_get  ConcurrentLinkedHashMap  thrpt    3  25862663.407 ��  7180846.734  ops/s
GetPutBenchmark.readwrite:readwrite_put  ConcurrentLinkedHashMap  thrpt    3   4609819.914 ��  2437033.702  ops/s
GetPutBenchmark.readwrite                       Coherence_Hybrid  thrpt    3  27352236.688 ��  2054858.487  ops/s
GetPutBenchmark.readwrite:readwrite_get         Coherence_Hybrid  thrpt    3  24477302.453 ��  1914848.604  ops/s
GetPutBenchmark.readwrite:readwrite_put         Coherence_Hybrid  thrpt    3   2874934.236 ��  1203791.003  ops/s
GetPutBenchmark.readwrite                               Ehcache3  thrpt    3  48735270.246 ��  2648040.014  ops/s
GetPutBenchmark.readwrite:readwrite_get                 Ehcache3  thrpt    3  44028929.911 ��  3239305.323  ops/s
GetPutBenchmark.readwrite:readwrite_put                 Ehcache3  thrpt    3   4706340.334 ��   726297.450  ops/s
GetPutBenchmark.readwrite                                  Guava  thrpt    3  19327134.687 ��  6330774.417  ops/s
GetPutBenchmark.readwrite:readwrite_get                    Guava  thrpt    3  18694672.970 ��  6600858.959  ops/s
GetPutBenchmark.readwrite:readwrite_put                    Guava  thrpt    3    632461.717 ��   624977.206  ops/s
GetPutBenchmark.write_only                     LinkedHashMap_Lru  thrpt    3  11242123.504 ��   295997.500  ops/s
GetPutBenchmark.write_only                              Caffeine  thrpt    3  35522090.287 �� 13561818.941  ops/s
GetPutBenchmark.write_only               ConcurrentLinkedHashMap  thrpt    3  18600282.773 �� 27731352.661  ops/s
GetPutBenchmark.write_only                      Coherence_Hybrid  thrpt    3   4552873.723 ��  7800355.132  ops/s
GetPutBenchmark.write_only                              Ehcache3  thrpt    3  17659195.512 ��  7963537.916  ops/s
GetPutBenchmark.write_only                                 Guava  thrpt    3  10129983.520 ��  1764954.824  ops/s

能有如此优秀表现,必然有一些非常值得研究的设计在里面,接下来我们一起研究下其独特的设计。

 驱逐策略

​  常见的淘汰策略有以下几种:

- Least Recently Used(LRU) - 核心是思想是最近被访问过的数据,将来被再次访问的概率大。存在热点数据的情况下,这种算法比较适合。但偶发性的、周期性批量操作容易导致数据污染。

- Least Frequently Used(LFU) - 核心是统计数据的访问频率,数据访问频率高的,将来再次被访问的概率大。这种算法需要维护所有数据的访问频次,并且每次访问时进行更新,缓存开销较大。对偶发浏览不太友好。

- FIFO 和 FILO: 队列和堆栈的思路,通常不用于缓存实现。

​  Caffeine 采用的是[Window TinyLFU](https://dl.acm.org/citation.cfm?id=3149371) (W-TinyLFU)算法,结合了LRU和LFU的优点。在统计频次方面,通过countMin sketch (一种紧凑的数据结构)解决了LFU频次统计占用空间。CountMin Sketch 采用的是Bloom Filter的设计思路。将一个key值映射做多个hash运算映射到多个bin,访问时对其所有bin进行+1操作;获取计数时只取多个bin中的最小值。通过这个matrix的运算将空间占用,计算性能和准确率控制在一个比较平衡的情况。

 

​ 利用CountMin Sketch统计识别出高频数据,并且在分段式LRU算法中作为过滤器,把高频的最近热数据识别出来。Caffeine 对频率统计在此上做了进一步的空间压缩 - 通常数字类型一般用64位long来表示,caffeine把long切分为16份每个数据进占用其中的4位。4位的最大值是15,也就是频次最大只能是15。caffeine认为这个数字范围已经能区分出数据的热度,并且在所有key的访问频次达到阈值的情况下,会对所有缓存key的频次除以2。

​  在数据保新方面,caffeine把缓存划分为俩大部分 LRU和Segmented LRU。

 

​ 新数据首先进入LRU区间,caffeine实现中叫window dequeue。在window dequeue满了的时候,lru被淘汰的数据会进入SLRU的probation dequeue。probation dequeue数据的访问频次达到一定次数时会进一步提升到 protected deque。但protected dequeue满了,降级一些数据到probation dequeue。但数据需要淘汰时,对probation dequeue的数据进行比较。probation dequeu队首部是最先进入队列的,队尾是最后加入队列的,队首和队尾的两个数据频次比较大小,小的数据被驱逐出去。

​  通过上述结构和频次自动衰减处理,caffeine节省了存储空间,同时平衡了访问频次和新鲜度俩个维度,能较好应对稀疏流量和短时超热点数据的情况。

 淘汰策略

​  Guava的读cache操作可能混杂着对过期数据的处理,对读性能影响较大。另一种做法用一个管理线程来对过期数据进行清除,但这种做法在读写的并发性上会有较大影响。

​  对缓存的并发访问被视为一个难题,因为在大多数策略中,每次访问都是对某些共享状态的写入。传统的解决方案是用一个锁来保护缓存。然后可以通过将缓存拆分为许多较小的独立区域来通过锁条带化来改进这一点,如concurrenthashmap分段式锁实现。但如果热点数据比较集中,那分段式锁依然不能达到较好的并发性能。

​  Caffeine借鉴了数据库的WAL设计思路,先写缓存再通过后台异步批量刷入缓存变更。读操作每个线程有一个单独的ring buffer存放读记录,写操作所有线程共享一个ring buffer。下面引用官方架构图:

注:图片来源 https://github.com/ben-manes/caffeine/wiki

 

时间轮过期算法

​  在处理不同过期时间的任务时,找到最早过期的任务跟当前时间比较,如果已过期则执行过期处理。问题在于如何高效的找到最早过期的任务。通常最值排序问题可以通过priority queue来解决,但priority queue 需要log(n),耗时长并且并发性能很差。数组的读写性能较好只需要O(1),可以把60秒内的任务拆解纯到60个格子中,每个格子有多个则对其进行拉链处理,类似hashmap的数组+链表结构。每次指针往前移动一格,格子内都是需要处理的数据。超过60秒范围内的数据则对其加个round属性,如70秒后表示的时 round = 1 = 70 /60, 在当前指针位置+10的地方插入。但则会引入一个新的问题,就是每次都需要对格子内的链表进行排序进行处理,如果格子内链表较长则带来的性能也较差。

因此用round来处理超范围的任务并不常用,通常是采用多层级的时间轮来处理。想象下我们的时钟,有多个指针,每个指针指向不同的轮子,并且每个轮子的粒度都不一样。当上一级任务处理完后,则从下一级更大粒度的轮子里面取出任务填充到细粒度的轮子里去。kafka、zookeeper、Linux内核均有类似实现,感兴趣的可以去了解下更多的实现细节,在此不作细述。

 

代码生成

​  为了尽量压缩缓存的内存footprint,caffeine甚至使用了代码生成工具,为每种配置策略生成了不同的数据节点node实现。在使用的时候,按需加载实例化。类的每个属性字段都是必须的,没有任何冗余字段,这样在实例化的时候内存占用最小化。

其按需加载的实现代码也是非常直白,根据不同特性如是否WeakValue拼接不同字符来拼出最终需要的类名,如下所示:

static <K, V> NodeFactory<K, V> newFactory(Caffeine<K, V> builder, boolean isAsync) {
    if (builder.interner) {
      return new Interned<>();
    }
    var className = getClassName(builder, isAsync);
    return loadFactory(className);
  }

  static String getClassName(Caffeine<?, ?> builder, boolean isAsync) {
    var className = new StringBuilder(Node.class.getPackageName()).append('.');
    if (builder.isStrongKeys()) {
      className.append('P');
    } else {
      className.append('F');
    }
    if (builder.isStrongValues()) {
      className.append('S');
    } else if (builder.isWeakValues()) {
      className.append('W');
    } else {
      className.append('D');
    }
    if (builder.expiresVariable()) {
      if (builder.refreshAfterWrite()) {
        className.append('A');
        if (builder.evicts()) {
          className.append('W');
        }
      } else {
        className.append('W');
      }
    } else {
      if (builder.expiresAfterAccess()) {
        className.append('A');
      }
      if (builder.expiresAfterWrite()) {
        className.append('W');
      }
    }
    if (builder.refreshAfterWrite()) {
      className.append('R');
    }
    if (builder.evicts()) {
      className.append('M');
      if (isAsync || (builder.isWeighted() && (builder.weigher != Weigher.singletonWeigher()))) {
        className.append('W');
      } else {
        className.append('S');
      }
    }
    return className.toString();
  }

最终按照拼接出来的名字,加载不同的node实现。

 

文章来自个人专栏
文章 | 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0