Package com.google.common.cache
Class LocalCache<K,V>
- java.lang.Object
-
- java.util.AbstractMap<K,V>
-
- com.google.common.cache.LocalCache<K,V>
-
- All Implemented Interfaces:
java.util.concurrent.ConcurrentMap<K,V>,java.util.Map<K,V>
class LocalCache<K,V> extends java.util.AbstractMap<K,V> implements java.util.concurrent.ConcurrentMap<K,V>The concurrent hash map implementation built byCacheBuilder.This implementation is heavily derived from revision 1.96 of ConcurrentHashMap.java.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) classLocalCache.AbstractCacheSet<T>(package private) static classLocalCache.AbstractReferenceEntry<K,V>(package private) static classLocalCache.AccessQueue<K,V>A custom queue for managing access order.(package private) static classLocalCache.EntryFactoryCreates new entries.(package private) classLocalCache.EntryIterator(package private) classLocalCache.EntrySet(package private) classLocalCache.HashIterator<T>(package private) classLocalCache.KeyIterator(package private) classLocalCache.KeySet(package private) static classLocalCache.LoadingSerializationProxy<K,V>Serializes the configuration of a LocalCache, reconstituting it as an LoadingCache using CacheBuilder upon deserialization.(package private) static classLocalCache.LoadingValueReference<K,V>(package private) static classLocalCache.LocalLoadingCache<K,V>(package private) static classLocalCache.LocalManualCache<K,V>(package private) static classLocalCache.ManualSerializationProxy<K,V>Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder upon deserialization.private static classLocalCache.NullEntry(package private) static classLocalCache.Segment<K,V>Segments are specialized versions of hash tables.(package private) static classLocalCache.SoftValueReference<K,V>References a soft value.(package private) static classLocalCache.Strength(package private) static classLocalCache.StrongAccessEntry<K,V>(package private) static classLocalCache.StrongAccessWriteEntry<K,V>(package private) static classLocalCache.StrongEntry<K,V>Used for strongly-referenced keys.(package private) static classLocalCache.StrongValueReference<K,V>References a strong value.(package private) static classLocalCache.StrongWriteEntry<K,V>(package private) classLocalCache.ValueIterator(package private) static interfaceLocalCache.ValueReference<K,V>A reference to a value.(package private) classLocalCache.Values(package private) static classLocalCache.WeakAccessEntry<K,V>(package private) static classLocalCache.WeakAccessWriteEntry<K,V>(package private) static classLocalCache.WeakEntry<K,V>Used for weakly-referenced keys.(package private) static classLocalCache.WeakValueReference<K,V>References a weak value.(package private) static classLocalCache.WeakWriteEntry<K,V>(package private) static classLocalCache.WeightedSoftValueReference<K,V>References a soft value.(package private) static classLocalCache.WeightedStrongValueReference<K,V>References a strong value.(package private) static classLocalCache.WeightedWeakValueReference<K,V>References a weak value.(package private) static classLocalCache.WriteQueue<K,V>A custom queue for managing eviction order.(package private) classLocalCache.WriteThroughEntryCustom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying map.
-
Field Summary
Fields Modifier and Type Field Description (package private) intconcurrencyLevelThe concurrency level.(package private) static intCONTAINS_VALUE_RETRIESNumber of (unsynchronized) retries in the containsValue method.(package private) CacheLoader<? super K,V>defaultLoaderThe default cache loader to use on loading operations.(package private) static java.util.Queue<?>DISCARDING_QUEUE(package private) static intDRAIN_MAXMaximum number of entries to be drained in a single cleanup run.(package private) static intDRAIN_THRESHOLDNumber of cache access operations that can be buffered per segment before the cache's recency ordering information is updated.(package private) LocalCache.EntryFactoryentryFactoryFactory used to create new entries.(package private) java.util.Set<java.util.Map.Entry<K,V>>entrySet(package private) longexpireAfterAccessNanosHow long after the last access to an entry the map will retain that entry.(package private) longexpireAfterWriteNanosHow long after the last write to an entry the map will retain that entry.(package private) AbstractCache.StatsCounterglobalStatsCounterAccumulates global cache statistics.(package private) Equivalence<java.lang.Object>keyEquivalenceStrategy for comparing keys.(package private) java.util.Set<K>keySet(package private) LocalCache.StrengthkeyStrengthStrategy for referencing keys.(package private) static java.util.logging.Loggerlogger(package private) static intMAX_SEGMENTSThe maximum number of segments to allow; used to bound constructor arguments.(package private) static intMAXIMUM_CAPACITYThe maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments.(package private) longmaxWeightThe maximum weight of this map.(package private) longrefreshNanosHow long after the last write an entry becomes a candidate for refresh.(package private) RemovalListener<K,V>removalListenerA listener that is invoked when an entry is removed due to expiration or garbage collection of soft/weak entries.(package private) java.util.Queue<RemovalNotification<K,V>>removalNotificationQueueEntries waiting to be consumed by the removal listener.(package private) intsegmentMaskMask value for indexing into segments.(package private) LocalCache.Segment<K,V>[]segmentsThe segments, each of which is a specialized hash table.(package private) intsegmentShiftShift value for indexing within segments.(package private) TickertickerMeasures time in a testable way.(package private) static LocalCache.ValueReference<java.lang.Object,java.lang.Object>UNSETPlaceholder.(package private) Equivalence<java.lang.Object>valueEquivalenceStrategy for comparing values.(package private) java.util.Collection<V>values(package private) LocalCache.StrengthvalueStrengthStrategy for referencing values.(package private) Weigher<K,V>weigherWeigher to weigh cache entries.
-
Constructor Summary
Constructors Constructor Description LocalCache(CacheBuilder<? super K,? super V> builder, CacheLoader<? super K,V> loader)Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidcleanUp()voidclear()Vcompute(K key, java.util.function.BiFunction<? super K,? super V,? extends V> function)VcomputeIfAbsent(K key, java.util.function.Function<? super K,? extends V> function)VcomputeIfPresent(K key, java.util.function.BiFunction<? super K,? super V,? extends V> function)(package private) static <K,V>
voidconnectAccessOrder(ReferenceEntry<K,V> previous, ReferenceEntry<K,V> next)(package private) static <K,V>
voidconnectWriteOrder(ReferenceEntry<K,V> previous, ReferenceEntry<K,V> next)booleancontainsKey(java.lang.Object key)booleancontainsValue(java.lang.Object value)(package private) ReferenceEntry<K,V>copyEntry(ReferenceEntry<K,V> original, ReferenceEntry<K,V> newNext)This method is a convenience for testing.(package private) LocalCache.Segment<K,V>createSegment(int initialCapacity, long maxSegmentWeight, AbstractCache.StatsCounter statsCounter)(package private) booleancustomWeigher()(package private) static <E> java.util.Queue<E>discardingQueue()Queue that discards all elements.java.util.Set<java.util.Map.Entry<K,V>>entrySet()(package private) booleanevictsBySize()(package private) booleanexpires()(package private) booleanexpiresAfterAccess()(package private) booleanexpiresAfterWrite()Vget(java.lang.Object key)(package private) Vget(K key, CacheLoader<? super K,V> loader)(package private) ImmutableMap<K,V>getAll(java.lang.Iterable<? extends K> keys)(package private) ImmutableMap<K,V>getAllPresent(java.lang.Iterable<?> keys)(package private) ReferenceEntry<K,V>getEntry(java.lang.Object key)Returns the internal entry for the specified key.VgetIfPresent(java.lang.Object key)(package private) VgetLiveValue(ReferenceEntry<K,V> entry, long now)Gets the value from an entry.VgetOrDefault(java.lang.Object key, V defaultValue)(package private) VgetOrLoad(K key)(package private) inthash(java.lang.Object key)(package private) voidinvalidateAll(java.lang.Iterable<?> keys)booleanisEmpty()(package private) booleanisExpired(ReferenceEntry<K,V> entry, long now)Returns true if the entry has expired.(package private) booleanisLive(ReferenceEntry<K,V> entry, long now)This method is a convenience for testing.java.util.Set<K>keySet()(package private) java.util.Map<K,V>loadAll(java.util.Set<? extends K> keys, CacheLoader<? super K,V> loader)Returns the result of callingCacheLoader.loadAll(java.lang.Iterable<? extends K>), or null ifloaderdoesn't implementloadAll.(package private) longlongSize()Vmerge(K key, V newValue, java.util.function.BiFunction<? super V,? super V,? extends V> function)(package private) ReferenceEntry<K,V>newEntry(K key, int hash, ReferenceEntry<K,V> next)This method is a convenience for testing.(package private) LocalCache.Segment<K,V>[]newSegmentArray(int ssize)(package private) LocalCache.ValueReference<K,V>newValueReference(ReferenceEntry<K,V> entry, V value, int weight)This method is a convenience for testing.(package private) static <K,V>
ReferenceEntry<K,V>nullEntry()(package private) static <K,V>
voidnullifyAccessOrder(ReferenceEntry<K,V> nulled)(package private) static <K,V>
voidnullifyWriteOrder(ReferenceEntry<K,V> nulled)(package private) voidprocessPendingNotifications()Notifies listeners that an entry has been automatically removed due to expiration, eviction, or eligibility for garbage collection.Vput(K key, V value)voidputAll(java.util.Map<? extends K,? extends V> m)VputIfAbsent(K key, V value)(package private) voidreclaimKey(ReferenceEntry<K,V> entry)(package private) voidreclaimValue(LocalCache.ValueReference<K,V> valueReference)(package private) booleanrecordsAccess()(package private) booleanrecordsTime()(package private) booleanrecordsWrite()(package private) voidrefresh(K key)(package private) booleanrefreshes()(package private) static intrehash(int h)Applies a supplemental hash function to a given hash code, which defends against poor quality hash functions.Vremove(java.lang.Object key)booleanremove(java.lang.Object key, java.lang.Object value)(package private) booleanremoveIf(java.util.function.BiPredicate<? super K,? super V> filter)Vreplace(K key, V value)booleanreplace(K key, V oldValue, V newValue)(package private) LocalCache.Segment<K,V>segmentFor(int hash)Returns the segment that should be used for a key with the given hash.intsize()private static <E> java.util.ArrayList<E>toArrayList(java.util.Collection<E> c)(package private) static <K,V>
LocalCache.ValueReference<K,V>unset()Singleton placeholder that indicates a value is being loaded.(package private) booleanusesAccessEntries()(package private) booleanusesAccessQueue()(package private) booleanusesKeyReferences()(package private) booleanusesValueReferences()(package private) booleanusesWriteEntries()(package private) booleanusesWriteQueue()java.util.Collection<V>values()
-
-
-
Field Detail
-
MAXIMUM_CAPACITY
static final int MAXIMUM_CAPACITY
The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments. MUST be a power of two<= 1<<30to ensure that entries are indexable using ints.- See Also:
- Constant Field Values
-
MAX_SEGMENTS
static final int MAX_SEGMENTS
The maximum number of segments to allow; used to bound constructor arguments.- See Also:
- Constant Field Values
-
CONTAINS_VALUE_RETRIES
static final int CONTAINS_VALUE_RETRIES
Number of (unsynchronized) retries in the containsValue method.- See Also:
- Constant Field Values
-
DRAIN_THRESHOLD
static final int DRAIN_THRESHOLD
Number of cache access operations that can be buffered per segment before the cache's recency ordering information is updated. This is used to avoid lock contention by recording a memento of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs.This must be a (2^n)-1 as it is used as a mask.
- See Also:
- Constant Field Values
-
DRAIN_MAX
static final int DRAIN_MAX
Maximum number of entries to be drained in a single cleanup run. This applies independently to the cleanup queue and both reference queues.- See Also:
- Constant Field Values
-
logger
static final java.util.logging.Logger logger
-
segmentMask
final int segmentMask
Mask value for indexing into segments. The upper bits of a key's hash code are used to choose the segment.
-
segmentShift
final int segmentShift
Shift value for indexing within segments. Helps prevent entries that end up in the same segment from also ending up in the same bucket.
-
segments
final LocalCache.Segment<K,V>[] segments
The segments, each of which is a specialized hash table.
-
concurrencyLevel
final int concurrencyLevel
The concurrency level.
-
keyEquivalence
final Equivalence<java.lang.Object> keyEquivalence
Strategy for comparing keys.
-
valueEquivalence
final Equivalence<java.lang.Object> valueEquivalence
Strategy for comparing values.
-
keyStrength
final LocalCache.Strength keyStrength
Strategy for referencing keys.
-
valueStrength
final LocalCache.Strength valueStrength
Strategy for referencing values.
-
maxWeight
final long maxWeight
The maximum weight of this map. UNSET_INT if there is no maximum.
-
expireAfterAccessNanos
final long expireAfterAccessNanos
How long after the last access to an entry the map will retain that entry.
-
expireAfterWriteNanos
final long expireAfterWriteNanos
How long after the last write to an entry the map will retain that entry.
-
refreshNanos
final long refreshNanos
How long after the last write an entry becomes a candidate for refresh.
-
removalNotificationQueue
final java.util.Queue<RemovalNotification<K,V>> removalNotificationQueue
Entries waiting to be consumed by the removal listener.
-
removalListener
final RemovalListener<K,V> removalListener
A listener that is invoked when an entry is removed due to expiration or garbage collection of soft/weak entries.
-
ticker
final Ticker ticker
Measures time in a testable way.
-
entryFactory
final LocalCache.EntryFactory entryFactory
Factory used to create new entries.
-
globalStatsCounter
final AbstractCache.StatsCounter globalStatsCounter
Accumulates global cache statistics. Note that there are also per-segments stats counters which must be aggregated to obtain a global stats view.
-
defaultLoader
final CacheLoader<? super K,V> defaultLoader
The default cache loader to use on loading operations.
-
UNSET
static final LocalCache.ValueReference<java.lang.Object,java.lang.Object> UNSET
Placeholder. Indicates that the value hasn't been set yet.
-
DISCARDING_QUEUE
static final java.util.Queue<?> DISCARDING_QUEUE
-
keySet
java.util.Set<K> keySet
-
values
java.util.Collection<V> values
-
-
Constructor Detail
-
LocalCache
LocalCache(CacheBuilder<? super K,? super V> builder, CacheLoader<? super K,V> loader)
Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
-
-
Method Detail
-
evictsBySize
boolean evictsBySize()
-
customWeigher
boolean customWeigher()
-
expires
boolean expires()
-
expiresAfterWrite
boolean expiresAfterWrite()
-
expiresAfterAccess
boolean expiresAfterAccess()
-
refreshes
boolean refreshes()
-
usesAccessQueue
boolean usesAccessQueue()
-
usesWriteQueue
boolean usesWriteQueue()
-
recordsWrite
boolean recordsWrite()
-
recordsAccess
boolean recordsAccess()
-
recordsTime
boolean recordsTime()
-
usesWriteEntries
boolean usesWriteEntries()
-
usesAccessEntries
boolean usesAccessEntries()
-
usesKeyReferences
boolean usesKeyReferences()
-
usesValueReferences
boolean usesValueReferences()
-
unset
static <K,V> LocalCache.ValueReference<K,V> unset()
Singleton placeholder that indicates a value is being loaded.
-
nullEntry
static <K,V> ReferenceEntry<K,V> nullEntry()
-
discardingQueue
static <E> java.util.Queue<E> discardingQueue()
Queue that discards all elements.
-
rehash
static int rehash(int h)
Applies a supplemental hash function to a given hash code, which defends against poor quality hash functions. This is critical when the concurrent hash map uses power-of-two length hash tables, that otherwise encounter collisions for hash codes that do not differ in lower or upper bits.- Parameters:
h- hash code
-
newEntry
ReferenceEntry<K,V> newEntry(K key, int hash, ReferenceEntry<K,V> next)
This method is a convenience for testing. Code should callLocalCache.Segment.newEntry(K, int, com.google.common.cache.ReferenceEntry<K, V>)directly.
-
copyEntry
ReferenceEntry<K,V> copyEntry(ReferenceEntry<K,V> original, ReferenceEntry<K,V> newNext)
This method is a convenience for testing. Code should callLocalCache.Segment.copyEntry(com.google.common.cache.ReferenceEntry<K, V>, com.google.common.cache.ReferenceEntry<K, V>)directly.
-
newValueReference
LocalCache.ValueReference<K,V> newValueReference(ReferenceEntry<K,V> entry, V value, int weight)
This method is a convenience for testing. Code should callLocalCache.Segment.setValue(com.google.common.cache.ReferenceEntry<K, V>, K, V, long)instead.
-
hash
int hash(java.lang.Object key)
-
reclaimValue
void reclaimValue(LocalCache.ValueReference<K,V> valueReference)
-
reclaimKey
void reclaimKey(ReferenceEntry<K,V> entry)
-
isLive
boolean isLive(ReferenceEntry<K,V> entry, long now)
This method is a convenience for testing. Code should callLocalCache.Segment.getLiveValue(com.google.common.cache.ReferenceEntry<K, V>, long)instead.
-
segmentFor
LocalCache.Segment<K,V> segmentFor(int hash)
Returns the segment that should be used for a key with the given hash.- Parameters:
hash- the hash code for the key- Returns:
- the segment
-
createSegment
LocalCache.Segment<K,V> createSegment(int initialCapacity, long maxSegmentWeight, AbstractCache.StatsCounter statsCounter)
-
getLiveValue
V getLiveValue(ReferenceEntry<K,V> entry, long now)
Gets the value from an entry. Returns null if the entry is invalid, partially-collected, loading, or expired. UnlikeLocalCache.Segment.getLiveValue(com.google.common.cache.ReferenceEntry<K, V>, long)this method does not attempt to cleanup stale entries. As such it should only be called outside of a segment context, such as during iteration.
-
isExpired
boolean isExpired(ReferenceEntry<K,V> entry, long now)
Returns true if the entry has expired.
-
connectAccessOrder
static <K,V> void connectAccessOrder(ReferenceEntry<K,V> previous, ReferenceEntry<K,V> next)
-
nullifyAccessOrder
static <K,V> void nullifyAccessOrder(ReferenceEntry<K,V> nulled)
-
connectWriteOrder
static <K,V> void connectWriteOrder(ReferenceEntry<K,V> previous, ReferenceEntry<K,V> next)
-
nullifyWriteOrder
static <K,V> void nullifyWriteOrder(ReferenceEntry<K,V> nulled)
-
processPendingNotifications
void processPendingNotifications()
Notifies listeners that an entry has been automatically removed due to expiration, eviction, or eligibility for garbage collection. This should be called every time expireEntries or evictEntry is called (once the lock is released).
-
newSegmentArray
final LocalCache.Segment<K,V>[] newSegmentArray(int ssize)
-
cleanUp
public void cleanUp()
-
isEmpty
public boolean isEmpty()
-
longSize
long longSize()
-
size
public int size()
-
get
public V get(java.lang.Object key)
-
get
V get(K key, CacheLoader<? super K,V> loader) throws java.util.concurrent.ExecutionException
- Throws:
java.util.concurrent.ExecutionException
-
getIfPresent
public V getIfPresent(java.lang.Object key)
-
getOrLoad
V getOrLoad(K key) throws java.util.concurrent.ExecutionException
- Throws:
java.util.concurrent.ExecutionException
-
getAllPresent
ImmutableMap<K,V> getAllPresent(java.lang.Iterable<?> keys)
-
getAll
ImmutableMap<K,V> getAll(java.lang.Iterable<? extends K> keys) throws java.util.concurrent.ExecutionException
- Throws:
java.util.concurrent.ExecutionException
-
loadAll
java.util.Map<K,V> loadAll(java.util.Set<? extends K> keys, CacheLoader<? super K,V> loader) throws java.util.concurrent.ExecutionException
Returns the result of callingCacheLoader.loadAll(java.lang.Iterable<? extends K>), or null ifloaderdoesn't implementloadAll.- Throws:
java.util.concurrent.ExecutionException
-
getEntry
ReferenceEntry<K,V> getEntry(java.lang.Object key)
Returns the internal entry for the specified key. The entry may be loading, expired, or partially collected.
-
refresh
void refresh(K key)
-
containsKey
public boolean containsKey(java.lang.Object key)
-
containsValue
public boolean containsValue(java.lang.Object value)
-
compute
public V compute(K key, java.util.function.BiFunction<? super K,? super V,? extends V> function)
-
computeIfAbsent
public V computeIfAbsent(K key, java.util.function.Function<? super K,? extends V> function)
-
computeIfPresent
public V computeIfPresent(K key, java.util.function.BiFunction<? super K,? super V,? extends V> function)
-
merge
public V merge(K key, V newValue, java.util.function.BiFunction<? super V,? super V,? extends V> function)
-
remove
public V remove(java.lang.Object key)
-
remove
public boolean remove(java.lang.Object key, java.lang.Object value)
-
clear
public void clear()
-
invalidateAll
void invalidateAll(java.lang.Iterable<?> keys)
-
keySet
public java.util.Set<K> keySet()
-
values
public java.util.Collection<V> values()
-
toArrayList
private static <E> java.util.ArrayList<E> toArrayList(java.util.Collection<E> c)
-
-