java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Caffeine缓存源码

浅析Java中的Caffeine缓存源码

作者:阿湯哥

这篇文章主要介绍了浅析Java中的Caffeine缓存源码,Caffeine是一个Java开发的高性能缓存库,它提供了一种简单而强大的方式来管理内存中的缓存数据,Caffeine的设计目标是提供快速、高效的缓存访问,同时保持简单易用的API,本文针对其部分源码做出解析,需要的朋友可以参考下

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);
    }
  }
}

到此这篇关于浅析Java中的Caffeine缓存源码的文章就介绍到这了,更多相关Caffeine缓存源码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文