Guava Cache 原理分析与最佳实践

210 阅读5分钟

.build(

CacheLoader.asyncReloading(new CacheLoader<String, String>() {

@Override

public String load(String key) {

return key;

}

@Override

public ListenableFuture reload(String key, String oldValue) throws Exception {

return super.reload(key, oldValue);

}

}, new ThreadPoolExecutor(5, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue<>()))

);

LocalCache 源码分析

先整体看下 Cache 的类结构,下面的这些子类表示了不同的创建方式本质还都是 LocalCache

【Cache 类图】

核心代码都在 LocalCache 这个文件中,并且通过这个继承关系可以看出 Guava Cache 的本质就是 ConcurrentMap。

【LocalCache 继承与实现】

在看源码之前先理一下流程,先理清思路。如果想直接看源码理解流程可以先跳过这张图 ~

【 get 缓存数据流程图】

这里核心理一下 Get 的流程,put 阶段比较简单就不做分析了。

  LocalCache#get

V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException {

int hash = hash(checkNotNull(key));

// 根据 hash 获取对应的 segment 然后从 segment 获取具体值

return segmentFor(hash).get(key, hash, loader);

}

  Segment#get

V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {

checkNotNull(key);

checkNotNull(loader);

try {

// count 表示在这个 segment 中存活的项目个数

if (count != 0) {

// 获取 segment 中的元素 (ReferenceEntry) 包含正在 load 的数据

ReferenceEntry<K, V> e = getEntry(key, hash);

if (e != null) {

long now = map.ticker.read();

// 获取缓存值,如果是 load,invalid,expired 返回 null,同时检查是否过期了,过期移除并返回 null

V value = getLiveValue(e, now);

if (value != null) {

// 记录访问时间

recordRead(e, now);

// 记录缓存命中一次

statsCounter.recordHits(1);

// 刷新缓存并返回缓存值 ,后面展开

return scheduleRefresh(e, key, hash, value, now, loader);

}

ValueReference<K, V> valueReference = e.getValueReference();

// 如果在 loading 等着 ,后面展开

if (valueReference.isLoading()) {

return waitForLoadingValue(e, key, valueReference);

}

}

}

// 走到这说明从来没写入过值 或者 值为 null 或者 过期(数据还没做清理),后面展开

return lockedGetOrLoad(key, hash, loader);

} catch (ExecutionException ee) {

Throwable cause = ee.getCause();

if (cause instanceof Error) {

throw new ExecutionError((Error) cause);

} else if (cause instanceof RuntimeException) {

throw new UncheckedExecutionException(cause);

}

throw ee;

} finally {

postReadCleanup();

}

}

  Segment#scheduleRefresh

// com.google.common.cache.LocalCache.Segment#scheduleRefresh

V scheduleRefresh(

ReferenceEntry<K, V> entry,

K key,

int hash,

V oldValue,

long now,

CacheLoader<? super K, V> loader) {

if (

// 配置了刷新策略 refreshAfterWrite

map.refreshes()

// 到刷新时间了

&& (now - entry.getWriteTime() > map.refreshNanos)

// 没在 loading

&& !entry.getValueReference().isLoading()) {

// 开始刷新,下面展开

V newValue = refresh(key, hash, loader, true);

if (newValue != null) {

return newValue;

}

}

return oldValue;

}

// com.google.common.cache.LocalCache.Segment#refresh

V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {

// 插入 loading 节点

final LoadingValueReference<K, V> loadingValueReference =

insertLoadingValueReference(key, hash, checkTime);

if (loadingValueReference == null) {

return null;

}

// 异步刷新,下面展开

ListenableFuture result = loadAsync(key, hash, loadingValueReference, loader);

if (result.isDone()) {

try {

return Uninterruptibles.getUninterruptibly(result);

} catch (Throwable t) {

// don't let refresh exceptions propagate; error was already logged

}

}

return null;

}

// com.google.common.cache.LocalCache.Segment#loadAsync

ListenableFuture loadAsync(

final K key,

final int hash,

final LoadingValueReference<K, V> loadingValueReference,

CacheLoader<? super K, V> loader) {

// 通过 loader 异步加载数据,下面展开

final ListenableFuture loadingFuture = loadingValueReference.loadFuture(key, loader);

loadingFuture.addListener(

new Runnable() {

@Override

public void run() {

try {

getAndRecordStats(key, hash, loadingValueReference, loadingFuture);

} catch (Throwable t) {

logger.log(Level.WARNING, "Exception thrown during refresh", t);

loadingValueReference.setException(t);

}

}

},

directExecutor());

return loadingFuture;

}

// com.google.common.cache.LocalCache.LoadingValueReference#loadFuture

public ListenableFuture loadFuture(K key, CacheLoader<? super K, V> loader) {

try {

stopwatch.start();

// oldValue 指在写入 loading 节点前这个位置的值,如果这个位置之前没有值 oldValue 会被赋值为 UNSET

// UNSET.get() 值为 null ,所以这个缓存项从来没有进入缓存需要同步 load 具体原因前面提到了,如果通过

// 异步 reload ,由于没有老值会导致其他线程返回的都是 null

V previousValue = oldValue.get();

if (previousValue == null) {

V newValue = loader.load(key);

return set(newValue) ? futureValue : Futures.immediateFuture(newValue);

}

// 异步 load

ListenableFuture newValue = loader.reload(key, previousValue);

if (newValue == null) {

return Futures.immediateFuture(null);

}

// To avoid a race, make sure the refreshed value is set into loadingValueReference

// before returning newValue from the cache query.

return transform(

newValue,

new com.google.common.base.Function<V, V>() {

@Override

public V apply(V newValue) {

LoadingValueReference.this.set(newValue);

return newValue;

}

},

directExecutor());

} catch (Throwable t) {

ListenableFuture result = setException(t) ? futureValue : fullyFailedFuture(t);

if (t instanceof InterruptedException) {

Thread.currentThread().interrupt();

}

return result;

}

}

  Segment#waitForLoadingValue

V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference)

throws ExecutionException {

// 首先你要是一个 loading 节点

if (!valueReference.isLoading()) {

throw new AssertionError();

}

checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);

// don't consider expiration as we're concurrent with loading

try {

V value = valueReference.waitForValue();

if (value == null) {

throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");

}

// re-read ticker now that loading has completed

long now = map.ticker.read();

recordRead(e, now);

return value;

} finally {

statsCounter.recordMisses(1);

}

}

// com.google.common.cache.LocalCache.LoadingValueReference#waitForValue

public V waitForValue() throws ExecutionException {

return getUninterruptibly(futureValue);

}

// com.google.common.util.concurrent.Uninterruptibles#getUninterruptibly

public static V getUninterruptibly(Future future) throws ExecutionException {

boolean interrupted = false;

try {

while (true) {

try {

// hang 住,如果该线程被打断了继续回去 hang 住等结果,直到有结果返回

return future.get();

} catch (InterruptedException e) {

interrupted = true;

}

}

} finally {

if (interrupted) {

Thread.currentThread().interrupt();

}

}

}

  Segment#lockedGetOrLoad

V lockedGetOrLoad(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {

ReferenceEntry<K, V> e;

ValueReference<K, V> valueReference = null;

LoadingValueReference<K, V> loadingValueReference = null;

boolean createNewEntry = true;

// 要对 segment 写操作 ,先加锁

lock();

try {

// re-read ticker once inside the lock

long now = map.ticker.read();

preWriteCleanup(now);

// 这里基本就是 HashMap 的代码,如果没有 segment 的数组下标冲突了就拉一个链表

int newCount = this.count - 1;

AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;

int index = hash & (table.length() - 1);

ReferenceEntry<K, V> first = table.get(index);

for (e = first; e != null; e = e.getNext()) {

K entryKey = e.getKey();

if (e.getHash() == hash

&& entryKey != null

&& map.keyEquivalence.equivalent(key, entryKey)) {

valueReference = e.getValueReference();

// 如果在加载中 不做任何处理

if (valueReference.isLoading()) {

createNewEntry = false;

} else {

V value = valueReference.get();

// 如果缓存项为 null 数据已经被删除,通知对应的 queue

if (value == null) {

enqueueNotification(

entryKey, hash, value, valueReference.getWeight(), RemovalCause.COLLECTED);

// 这个是 double check 如果缓存项过期 数据没被删除,通知对应的 queue

} else if (map.isExpired(e, now)) {

// This is a duplicate check, as preWriteCleanup already purged expired

// entries, but let's accommodate an incorrect expiration queue.

enqueueNotification(

entryKey, hash, value, valueReference.getWeight(), RemovalCause.EXPIRED);

// 再次看到的时候这个位置有值了直接返回

} else {

recordLockedRead(e, now);

statsCounter.recordHits(1);

return value;

}

// immediately reuse invalid entries

writeQueue.remove(e);

accessQueue.remove(e);

this.count = newCount; // write-volatile

}

break;

}

}

// 没有 loading ,创建一个 loading 节点

if (createNewEntry) {

loadingValueReference = new LoadingValueReference<>();

if (e == null) {

e = newEntry(key, hash, first);

e.setValueReference(loadingValueReference);

table.set(index, e);

} else {

e.setValueReference(loadingValueReference);

}

}

} finally {

unlock();

postWriteCleanup();

最后

面试前一定少不了刷题,为了方便大家复习,我分享一波个人整理的面试大全宝典

  • Java核心知识整理

2020年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多

Java核心知识

  • Spring全家桶(实战系列)

2020年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多

  • 其他电子书资料

2020年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多

Step3:刷题

既然是要面试,那么就少不了刷题,实际上春节回家后,哪儿也去不了,我自己是刷了不少面试题的,所以在面试过程中才能够做到心中有数,基本上会清楚面试过程中会问到哪些知识点,高频题又有哪些,所以刷题是面试前期准备过程中非常重要的一点。

以下是我私藏的面试题库:

2020年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多

相关阅读docs.qq.com/doc/DSmxTbFJ1cmN1R2dB