1. 程式人生 > >Guava Cache 研究

Guava Cache 研究

,Guava Cache其核心資料結構大體上和ConcurrentHashMap一致,具體細節上會有些區別。功能上,ConcurrentMap會一直儲存所有新增的元素,直到顯式地移除.相對地,Guava Cache為了限制記憶體佔用,通常都設定為自動回收元素.在某些場景下,儘管它不回收元素,也是很有用的,因為它會自動載入快取.

class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>

子類 LocalLoadingCache

  static
class LocalLoadingCache<K, V> extends LocalManualCache<K, V> implements LoadingCache<K, V> { LocalLoadingCache(CacheBuilder<? super K, ? super V> builder, CacheLoader<? super K, V> loader) { super(new LocalCache<K, V>(builder, checkNotNull(loader))); }

在使用get方法的時候,如果快取不存在該key或者key過期等,則呼叫getOrLoad 方法載入資料;

// LoadingCache methods

    @Override
    public V get(K key) throws ExecutionException {
      return localCache.getOrLoad(key);
    }

在LocalCache中確實提供了兩種類,一個是支援自動載入value的LocalLoadingCache 和只能在鍵值找不到的時候手動呼叫獲取值方法的LocalManualCache。

/**
   * Builds a cache, which either returns an already-loaded value for a given key or atomically
   * computes or retrieves it using the supplied {@code
CacheLoader}. If another thread is currently * loading the value for this key, simply waits for that thread to finish and returns its * loaded value. Note that multiple threads can concurrently load values for distinct keys. * * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be * invoked again to create multiple independent caches. * * @param loader the cache loader used to obtain new values * @return a cache having the requested features */
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build( CacheLoader<? super K1, V1> loader) { checkWeightWithWeigher(); return new LocalCache.LocalLoadingCache<K1, V1>(this, loader); } /** * Builds a cache which does not automatically load values when keys are requested. * * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a * {@code CacheLoader}. * * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be * invoked again to create multiple independent caches. * * @return a cache having the requested features * @since 11.0 */ public <K1 extends K, V1 extends V> Cache<K1, V1> build() { checkWeightWithWeigher(); checkNonLoadingCache(); return new LocalCache.LocalManualCache<K1, V1>(this); }

Guava Cache的實現,核心資料結構和演算法都是和JDK 1.6版本的ConcurrentHashMap一致