Caffeine源码浅析

1. Caffenie的核心类图

在这里插入图片描述

2. Caffenie缓存的分类

Caffenie从同步-异步、手工加载-自动加载、有界-无界三个维度,可以分为8中缓存类型。
在这里插入图片描述

3. LocalCacheFactory缓存工厂

com.github.benmanes.caffeine.cache.LocalCacheFactory#newBoundedLocalCache (只针对有界队列)

static <K, V> BoundedLocalCache<K, V> newBoundedLocalCache(Caffeine<K, V> builder,
  @Nullable CacheLoader<? super K, V> cacheLoader, boolean async) {
  StringBuilder sb = new StringBuilder("com.github.benmanes.caffeine.cache.");
  if (builder.isStrongKeys()) {
    sb.append('S');
  } else {
    sb.append('W');
  }
  if (builder.isStrongValues()) {
    sb.append('S');
  } else {
    sb.append('I');
  }
  if (builder.removalListener != null) {
    sb.append('L');
  }
  if (builder.isRecordingStats()) {
    sb.append('S');
  }
  if (builder.evicts()) {
    sb.append('M');
    if (builder.isWeighted()) {
      sb.append('W');
    } else {
      sb.append('S');
    }
  }
  if (builder.expiresAfterAccess() || builder.expiresVariable()) {
    sb.append('A');
  }
  if (builder.expiresAfterWrite()) {
    sb.append('W');
  }
  if (builder.refreshes()) {
    sb.append('R');
  }
  try {
    Class<?> clazz = LocalCacheFactory.class.getClassLoader().loadClass(sb.toString());
    Constructor<?> ctor = clazz.getDeclaredConstructor(Caffeine.class, CacheLoader.class, boolean.class);
    @SuppressWarnings("unchecked")
    BoundedLocalCache<K, V> factory = (BoundedLocalCache<K, V>) ctor.newInstance(builder, cacheLoader, async);
    return factory;
  } catch (ReflectiveOperationException e) {
    throw new IllegalStateException(sb.toString(), e);
  }
}

4. 缓存维护

com.github.benmanes.caffeine.cache.BoundedLocalCache#maintenance

/**
 * Performs the pending maintenance work and sets the state flags during processing to avoid
 * excess scheduling attempts. The read buffer, write buffer, and reference queues are
 * drained, followed by expiration, and size-based eviction.
 *
 * @param task an additional pending task to run, or {@code null} if not present
 */
@GuardedBy("evictionLock")
void maintenance(@Nullable Runnable task) {
  lazySetDrainStatus(PROCESSING_TO_IDLE);

  try {
    drainReadBuffer();

    drainWriteBuffer();
    if (task != null) {
      task.run();
    }

    drainKeyReferences();
    drainValueReferences();

    expireEntries();
    evictEntries();

    climb();
  } finally {
    if ((drainStatus() != PROCESSING_TO_IDLE) || !casDrainStatus(PROCESSING_TO_IDLE, IDLE)) {
      lazySetDrainStatus(REQUIRED);
    }
  }
}

参考

https://github.com/ben-manes/caffeine/wiki
Caffeine 缓存
Caffeine Cache实战
深入解密来自未来的缓存-Caffeine
SpringBoot项目开发(二十):Caffeine本地缓存
论文《TinyLFU: A Highly Ecient Cache Admission Policy》阅读笔记
现代化的缓存设计方案
Caffeine Cache 进程缓存之王

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值