- cache 接口
主要有這幾個方法 :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 是個抽象類 苞慢,繼承了Cache
- 如果調用AbstractCache的get、put英妓、size挽放、invalidate、invalidateAll()蔓纠、stats()辑畦、asMap()方法,會拋出UnsupportedOperationException()異常腿倚。
- getAllPresent 返回的ImmutableMap為LinkedHashMap纯出。
當插入一串新數(shù)據(jù)時,會首先判斷是否當前插入的是否存在于之前已經插入的數(shù)據(jù)中 敷燎,如果不存在暂筝,繼續(xù)判斷是否已經當前對象中 ,如果不是懈叹,就插入結果集合乖杠。最后返回結果集合 分扎。 - invalidateAll(Iterable<?> keys)澄成,調用invalidate刪除數(shù)據(jù)
- 里面有一個SimpleStatsCounter內部類 ,實現(xiàn)了AbstractCache.StatsCounter接口畏吓。
同時定義了一個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操作。包括命中計數(shù)菲饼、未命中計數(shù)肾砂、裝載成功計數(shù)、裝載異常計數(shù)宏悦、總共裝載計數(shù)镐确、換出計數(shù)包吝。(
long hitCount, long missCount, long loadSuccessCount, long loadExceptionCount, long totalLoadTime, long evictionCount)
snapshot()函數(shù)將返回當前所有計數(shù)的數(shù)量。
incrementBy(AbstractCache.StatsCounter other)可以直接在一系列的計數(shù)中加上另外一個AbstractCache.StatsCounter的數(shù)量源葫。
AbstractLoadingCache是個抽象類诗越,繼承了AbstractCache.
方法 | 含義 |
---|---|
V getUnchecked(K key) | 暫時不理解 |
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) | 在內部創(chuàng)建了一個鏈表哈希map,將傳入的值放入linkHashMap中,用迭代器進行遍歷息堂。最后返回ImmutableMap類型的對象嚷狞。 |
V apply(K key) | 調用getUnchecked返回對象 |
refresh | 拋出UnsupportedOperationException異常 |
CacheBuilder
在cacheBuilder的文檔中提到,一個LoadingCache和Cache的實例的構造者應該具有以下特點:
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
中文翻譯就是
- 自動裝載實體到內存荣堰。
- 當超過最大內存時床未,會清除最近最少使用的。
- 按照上次訪問或寫入的時間來測量條目是否達到過期時間振坚。
- 鍵自動包裹在弱引用中薇搁。
- 值自動包裹到強引用或軟引用中。
- 刪除或換出數(shù)據(jù)時有通知
- 積累緩存訪問的數(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)建高速緩存屡拨。默認情況下只酥,CacheBuilder創(chuàng)建的緩存實例不會執(zhí)行任何類型的逐出。
一個使用cachebuilder的實例:
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)建方式是等價的呀狼。
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
.
大概意思如下:
- 返回的cache的實現(xiàn)類似于ConcurrentHashMap的哈希表裂允。
它實現(xiàn)了LoadingCache和Cache的所有接口。 - asMap視圖是弱一致的迭代器哥艇。這意味著他們是線程安全的绝编。它沒有定義這些改變,當影響到迭代器時貌踏,這些迭代器絕不會拋出ConcurrentModificationException異常十饥。
- 已經換出的數(shù)據(jù)也可能被Cache.size()方法在計數(shù)時計算,但是不能對其進行讀寫操作祖乳。
-
CacheBuilder<K,V> maximumWeight(long weight)這個方法確定了緩存包含的對象的最大權重逗堵。
注意權重只是用來決定緩存是否已經超過其最大容量。它對于接下來要將哪個對象換出內存沒有影響眷昆。
拋出的異常
- IllegalArgumentException假如設置的權值為負
- IllegalStateException假如已經設置了最大權重或者最大容量
函數(shù) | 返回值 | 說明 |
---|---|---|
build() | Cache<K1,V1> | 創(chuàng)建緩存蜒秤,此緩存在請求關鍵字時,不會自動加載值 |
build(CacheLoader<? super K1,V1> loader) | LoadingCache<K1,V1> | 創(chuàng)建緩存亚斋。它可以返回給定鍵的已經加載的值作媚,也可以使用提供的CacheLoader來進行原子計算或檢索它 |
ticker | CacheBuilder<K,V> | 指定一個納秒精度時間源,用于確定條目何時過期帅刊。 |
concurrencyLevel(int concurrencyLevel) | CacheBuilder<K,V> | 指導更新操作之間允許的并發(fā)性纸泡。 |
initialCapacity(int initialCapacity) | CacheBuilder<K,V> | 設置內部哈希表的最小長度。 |
maximumSize(long size) | CacheBuilder<K,V> | 指定緩存可能包含的最大條目數(shù)赖瞒。 |
maximumWeight(long weight) | CacheBuilder<K,V> | 指定緩存可能包含的條目的最大權重女揭。 |
newBuilder() | static CacheBuilder<Object,Object> | 構造一個新的CacheBuilder實例蚤假,具有默認設置,包括強大的鍵吧兔,強大的值勤哗,并且沒有任何自動驅逐。 |
recordStats() | CacheBuilder<K,V> | 在緩存的操作期間啟用CacheStats的累積 |
refreshAfterWrite(long duration, TimeUnit unit) | CacheBuilder<K,V> | 指定在條目創(chuàng)建后經過固定持續(xù)時間或最近更換其值后掩驱,活動條目符合自動刷新的條件芒划。 |
from(String spec) | static CacheBuilder<Object,Object> | 使用規(guī)范中指定的設置構造新的CacheBuilder實例 |
removalListener(RemovalListener<? super K1,? super V1> listener) | <K1 extends K,V1 extends V> CacheBuilder<K1,V1> | 指定一個監(jiān)聽器實例,高速緩存在任何情況下欧穴,每次刪除一個條目時應該通知它民逼。 |
softValues() | CacheBuilder<K,V> | 指定存儲在緩存中的每個值(非鍵)都應該包裝在SoftReference中(默認情況下铜涉,使用強引用)蜕企。 |