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 进程缓存之王