GUAVA Cache源碼閱讀-cache、AbstractCache 、AbstractLoadingCache、CacheBuilder

  1. cache 接口
    主要有這幾個(gè)方法 :
    • V getIfPresent(Object var1);

    • V get(K var1, Callable<? extends V> var2) throws ExecutionException;

    • ImmutableMap<K, V> getAllPresent(Iterable<?> var1);

    • void put(K var1, V var2);

    • void putAll(Map<? extends K, ? extends V> var1);

    • void invalidate(Object var1);

    • void invalidateAll(Iterable<?> var1);

    • void invalidateAll();

    • long size();

    • CacheStats stats();

    • ConcurrentMap<K, V> asMap();

    • void cleanUp();


AbstractCache 是個(gè)抽象類 ,繼承了Cache

  1. 如果調(diào)用AbstractCache的get、put、size、invalidate、invalidateAll()、stats()、asMap()方法,會(huì)拋出UnsupportedOperationException()異常。
  2. getAllPresent 返回的ImmutableMap為LinkedHashMap。
    當(dāng)插入一串新數(shù)據(jù)時(shí),會(huì)首先判斷是否當(dāng)前插入的是否存在于之前已經(jīng)插入的數(shù)據(jù)中 ,如果不存在,繼續(xù)判斷是否已經(jīng)當(dāng)前對象中 ,如果不是,就插入結(jié)果集合。最后返回結(jié)果集合 。
  3. invalidateAll(Iterable<?> keys),調(diào)用invalidate刪除數(shù)據(jù)
  4. 里面有一個(gè)SimpleStatsCounter內(nèi)部類 ,實(shí)現(xiàn)了AbstractCache.StatsCounter接口。
    同時(shí)定義了一個(gè)LongAddable 接口。
    statsCounter 接口
    public interface StatsCounter
    {
    void recordHits(int var1);
    void recordMisses(int var1);
    void recordLoadSuccess(long var1);
    void recordLoadException(long var1);
    void recordEviction();
    CacheStats snapshot();
    }
    LongAddable 接口
    interface LongAddable
    {
    void increment();
    void add(long var1);
    long sum();
    }
    SimpleStateCounter中定義了一系列LongAddAble操作。包括命中計(jì)數(shù)、未命中計(jì)數(shù)、裝載成功計(jì)數(shù)、裝載異常計(jì)數(shù)、總共裝載計(jì)數(shù)、換出計(jì)數(shù)。(
    long hitCount, long missCount, long loadSuccessCount, long loadExceptionCount, long totalLoadTime, long evictionCount)
    snapshot()函數(shù)將返回當(dāng)前所有計(jì)數(shù)的數(shù)量。
    incrementBy(AbstractCache.StatsCounter other)可以直接在一系列的計(jì)數(shù)中加上另外一個(gè)AbstractCache.StatsCounter的數(shù)量。

AbstractLoadingCache是個(gè)抽象類,繼承了AbstractCache.

方法 含義
V getUnchecked(K key) 暫時(shí)不理解
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) 在內(nèi)部創(chuàng)建了一個(gè)鏈表哈希map,將傳入的值放入linkHashMap中,用迭代器進(jìn)行遍歷。最后返回ImmutableMap類型的對象。
V apply(K key) 調(diào)用getUnchecked返回對象
refresh 拋出UnsupportedOperationException異常

CacheBuilder
在cacheBuilder的文檔中提到,一個(gè)LoadingCache和Cache的實(shí)例的構(gòu)造者應(yīng)該具有以下特點(diǎn):
A builder of LoadingCache and Cache instances having any combination of the following features:

  • automatic loading of entries into the cache
  • least-recently-used eviction when a maximum size is exceeded
  • time-based expiration of entries, measured since last access or last write
  • keys automatically wrapped in [weak]references
  • values automatically wrapped in [weak] or [soft] references
  • notification of evicted (or otherwise removed) entries
  • accumulation of cache access statistics

中文翻譯就是

  • 自動(dòng)裝載實(shí)體到內(nèi)存。
  • 當(dāng)超過最大內(nèi)存時(shí),會(huì)清除最近最少使用的
  • 按照上次訪問或?qū)懭氲臅r(shí)間來測量條目是否達(dá)到過期時(shí)間。
  • 鍵自動(dòng)包裹在弱引用中。
  • 值自動(dòng)包裹到強(qiáng)引用或軟引用中。
  • 刪除或換出數(shù)據(jù)時(shí)有通知
  • 積累緩存訪問的數(shù)據(jù)

These features are all optional; caches can be created using all or none of them. By default cache instances created by CacheBuilder will not perform any type of eviction.

這些功能都是可選的;可以使用全部或不創(chuàng)建高速緩存。默認(rèn)情況下,CacheBuilder創(chuàng)建的緩存實(shí)例不會(huì)執(zhí)行任何類型的逐出。
一個(gè)使用cachebuilder的實(shí)例:

  LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
   .maximumSize(10000)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   .removalListener(MY_LISTENER)
   .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) throws AnyException {
           return createExpensiveGraph(key);
         }
       }); 

還有一種創(chuàng)建方式

    String spec = "maximumSize=10000,expireAfterWrite=10m";
     LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
    .removalListener(MY_LISTENER)
    .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });

這兩種創(chuàng)建方式是等價(jià)的。

The returned cache is implemented as a hash table with similar performance characteristics to ConcurrentHashMap
. It implements all optional operations of the LoadingCache and Cache interfaces. The asMap
view (and its collection views) have weakly consistent iterators. This means that they are safe for concurrent use, but if other threads modify the cache after the iterator is created, it is undefined which of these changes, if any, are reflected in that iterator. These iterators never throw ConcurrentModificationException
.

大概意思如下:

  1. 返回的cache的實(shí)現(xiàn)類似于ConcurrentHashMap的哈希表。
    它實(shí)現(xiàn)了LoadingCache和Cache的所有接口。
  2. asMap視圖是弱一致的迭代器。這意味著他們是線程安全的。它沒有定義這些改變,當(dāng)影響到迭代器時(shí),這些迭代器絕不會(huì)拋出ConcurrentModificationException異常。
  3. 已經(jīng)換出的數(shù)據(jù)也可能被Cache.size()方法在計(jì)數(shù)時(shí)計(jì)算,但是不能對其進(jìn)行讀寫操作。
  4. CacheBuilder<K,V> maximumWeight(long weight)這個(gè)方法確定了緩存包含的對象的最大權(quán)重。
    注意權(quán)重只是用來決定緩存是否已經(jīng)超過其最大容量。它對于接下來要將哪個(gè)對象換出內(nèi)存沒有影響。
    拋出的異常
函數(shù) 返回值 說明
build() Cache<K1,V1> 創(chuàng)建緩存,此緩存在請求關(guān)鍵字時(shí),不會(huì)自動(dòng)加載值
build(CacheLoader<? super K1,V1> loader) LoadingCache<K1,V1> 創(chuàng)建緩存。它可以返回給定鍵的已經(jīng)加載的值,也可以使用提供的CacheLoader來進(jìn)行原子計(jì)算或檢索它
ticker CacheBuilder<K,V> 指定一個(gè)納秒精度時(shí)間源,用于確定條目何時(shí)過期。
concurrencyLevel(int concurrencyLevel) CacheBuilder<K,V> 指導(dǎo)更新操作之間允許的并發(fā)性。
initialCapacity(int initialCapacity) CacheBuilder<K,V> 設(shè)置內(nèi)部哈希表的最小長度。
maximumSize(long size) CacheBuilder<K,V> 指定緩存可能包含的最大條目數(shù)。
maximumWeight(long weight) CacheBuilder<K,V> 指定緩存可能包含的條目的最大權(quán)重。
newBuilder() static CacheBuilder<Object,Object> 構(gòu)造一個(gè)新的CacheBuilder實(shí)例,具有默認(rèn)設(shè)置,包括強(qiáng)大的鍵,強(qiáng)大的值,并且沒有任何自動(dòng)驅(qū)逐。
recordStats() CacheBuilder<K,V> 在緩存的操作期間啟用CacheStats的累積
refreshAfterWrite(long duration, TimeUnit unit) CacheBuilder<K,V> 指定在條目創(chuàng)建后經(jīng)過固定持續(xù)時(shí)間或最近更換其值后,活動(dòng)條目符合自動(dòng)刷新的條件。
from(String spec) static CacheBuilder<Object,Object> 使用規(guī)范中指定的設(shè)置構(gòu)造新的CacheBuilder實(shí)例
removalListener(RemovalListener<? super K1,? super V1> listener) <K1 extends K,V1 extends V> CacheBuilder<K1,V1> 指定一個(gè)監(jiān)聽器實(shí)例,高速緩存在任何情況下,每次刪除一個(gè)條目時(shí)應(yīng)該通知它。
softValues() CacheBuilder<K,V> 指定存儲(chǔ)在緩存中的每個(gè)值(非鍵)都應(yīng)該包裝在SoftReference中(默認(rèn)情況下,使用強(qiáng)引用)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,923評(píng)論 18 139
  • 為誰而作?是一件非常重要的事情。 考慮到作是一個(gè)非常寬泛的動(dòng)詞,我們暫且把此處的“作”,看作是創(chuàng)作的作。如果分得再...
    崗鑒閱讀 355評(píng)論 0 3
  • 我們每個(gè)人都有一個(gè)夢想,希望未來的家庭生活充滿了智能,就如同科幻小說里描寫的那樣,至少也應(yīng)該有個(gè)“大白”陪伴。實(shí)際...
    花捧娛樂vlog視頻植入閱讀 369評(píng)論 0 0
  • 各位小伙伴們大家好,這幾天弱弱的看了看老掉牙的支持向量機(jī)(Support Vector Machine, SVM)...
    云時(shí)之間閱讀 1,409評(píng)論 1 3
  • 今天和大米結(jié)束了她喜歡的《窗邊的小豆豆》,開始了《瘋狂的學(xué)校》。一所日本學(xué)校的學(xué)校生活,一所美國的學(xué)校生活;兩個(gè)國...
    悅米時(shí)光閱讀 158評(píng)論 0 0