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:
ConcurrentMap<K,
,V> Map<K,
V>
The concurrent hash map implementation built by
CacheBuilder
.
This implementation is heavily derived from revision 1.96 of ConcurrentHashMap.java.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) class
(package private) static class
(package private) static final class
A custom queue for managing access order.(package private) static class
(package private) static enum
Creates new entries.(package private) final class
(package private) final class
(package private) class
(package private) final class
(package private) final class
(package private) static final class
Serializes the configuration of a LocalCache, reconstituting it as an LoadingCache using CacheBuilder upon deserialization.(package private) static class
(package private) static class
(package private) static class
(package private) static class
Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder upon deserialization.private static enum
(package private) static class
Segments are specialized versions of hash tables.(package private) static class
References a soft value.(package private) static enum
(package private) static final class
(package private) static final class
(package private) static class
Used for strongly-referenced keys.(package private) static class
References a strong value.(package private) static final class
(package private) final class
(package private) static interface
A reference to a value.(package private) final class
(package private) static final class
(package private) static final class
(package private) static class
Used for weakly-referenced keys.(package private) static class
References a weak value.(package private) static final class
(package private) static final class
References a soft value.(package private) static final class
References a strong value.(package private) static final class
References a weak value.(package private) static final class
A custom queue for managing eviction order.(package private) final class
Custom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying map.Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K,
V>, AbstractMap.SimpleImmutableEntry<K, V> -
Field Summary
FieldsModifier and TypeFieldDescription(package private) final int
The concurrency level.(package private) static final int
Number of (unsynchronized) retries in the containsValue method.(package private) final CacheLoader
<? super K, V> The default cache loader to use on loading operations.(package private) static final Queue
<?> (package private) static final int
Maximum number of entries to be drained in a single cleanup run.(package private) static final int
Number of cache access operations that can be buffered per segment before the cache's recency ordering information is updated.(package private) final LocalCache.EntryFactory
Factory used to create new entries.(package private) final long
How long after the last access to an entry the map will retain that entry.(package private) final long
How long after the last write to an entry the map will retain that entry.(package private) final AbstractCache.StatsCounter
Accumulates global cache statistics.(package private) final Equivalence
<Object> Strategy for comparing keys.(package private) final LocalCache.Strength
Strategy for referencing keys.(package private) static final Logger
(package private) static final int
The maximum number of segments to allow; used to bound constructor arguments.(package private) static final int
The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments.(package private) final long
The maximum weight of this map.(package private) final long
How long after the last write an entry becomes a candidate for refresh.(package private) final RemovalListener
<K, V> A listener that is invoked when an entry is removed due to expiration or garbage collection of soft/weak entries.(package private) final Queue
<RemovalNotification<K, V>> Entries waiting to be consumed by the removal listener.(package private) final int
Mask value for indexing into segments.(package private) final LocalCache.Segment<K,
V>[] The segments, each of which is a specialized hash table.(package private) final int
Shift value for indexing within segments.(package private) final Ticker
Measures time in a testable way.(package private) static final LocalCache.ValueReference
<Object, Object> Placeholder.(package private) final Equivalence
<Object> Strategy for comparing values.(package private) Collection
<V> (package private) final LocalCache.Strength
Strategy for referencing values.Weigher to weigh cache entries. -
Constructor Summary
ConstructorsConstructorDescriptionLocalCache
(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
Modifier and TypeMethodDescriptionvoid
cleanUp()
void
clear()
computeIfAbsent
(K key, Function<? super K, ? extends V> function) computeIfPresent
(K key, BiFunction<? super K, ? super V, ? extends V> function) (package private) static <K,
V> void connectAccessOrder
(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) (package private) static <K,
V> void connectWriteOrder
(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) boolean
containsKey
(Object key) boolean
containsValue
(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) boolean
(package private) static <E> Queue
<E> Queue that discards all elements.entrySet()
(package private) boolean
(package private) boolean
expires()
(package private) boolean
(package private) boolean
(package private) V
get
(K key, CacheLoader<? super K, V> loader) (package private) ImmutableMap
<K, V> (package private) ImmutableMap
<K, V> getAllPresent
(Iterable<?> keys) (package private) ReferenceEntry
<K, V> Returns the internal entry for the specified key.getIfPresent
(Object key) (package private) V
getLiveValue
(ReferenceEntry<K, V> entry, long now) Gets the value from an entry.getOrDefault
(Object key, V defaultValue) (package private) V
(package private) int
(package private) void
invalidateAll
(Iterable<?> keys) boolean
isEmpty()
(package private) boolean
isExpired
(ReferenceEntry<K, V> entry, long now) Returns true if the entry has expired.(package private) boolean
isLive
(ReferenceEntry<K, V> entry, long now) This method is a convenience for testing.keySet()
Returns the result of callingCacheLoader.loadAll(java.lang.Iterable<? extends K>)
, or null ifloader
doesn't implementloadAll
.(package private) long
longSize()
(package private) ReferenceEntry
<K, V> newEntry
(K key, int hash, ReferenceEntry<K, V> next) This method is a convenience for testing.(package private) final 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> (package private) static <K,
V> void nullifyAccessOrder
(ReferenceEntry<K, V> nulled) (package private) static <K,
V> void nullifyWriteOrder
(ReferenceEntry<K, V> nulled) (package private) void
Notifies listeners that an entry has been automatically removed due to expiration, eviction, or eligibility for garbage collection.void
putIfAbsent
(K key, V value) (package private) void
reclaimKey
(ReferenceEntry<K, V> entry) (package private) void
reclaimValue
(LocalCache.ValueReference<K, V> valueReference) (package private) boolean
(package private) boolean
(package private) boolean
(package private) void
(package private) boolean
(package private) static int
rehash
(int h) Applies a supplemental hash function to a given hash code, which defends against poor quality hash functions.boolean
(package private) boolean
removeIf
(BiPredicate<? super K, ? super V> filter) boolean
(package private) LocalCache.Segment
<K, V> segmentFor
(int hash) Returns the segment that should be used for a key with the given hash.int
size()
(package private) static <K,
V> LocalCache.ValueReference <K, V> unset()
Singleton placeholder that indicates a value is being loaded.(package private) boolean
(package private) boolean
(package private) boolean
(package private) boolean
(package private) boolean
(package private) boolean
values()
Methods inherited from class java.util.AbstractMap
clone, equals, hashCode, toString
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.concurrent.ConcurrentMap
forEach, replaceAll
-
Field Details
-
MAXIMUM_CAPACITY
static final int MAXIMUM_CAPACITYThe maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments. MUST be a power of two<= 1<<30
to ensure that entries are indexable using ints.- See Also:
-
MAX_SEGMENTS
static final int MAX_SEGMENTSThe maximum number of segments to allow; used to bound constructor arguments.- See Also:
-
CONTAINS_VALUE_RETRIES
static final int CONTAINS_VALUE_RETRIESNumber of (unsynchronized) retries in the containsValue method.- See Also:
-
DRAIN_THRESHOLD
static final int DRAIN_THRESHOLDNumber 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:
-
DRAIN_MAX
static final int DRAIN_MAXMaximum number of entries to be drained in a single cleanup run. This applies independently to the cleanup queue and both reference queues.- See Also:
-
logger
-
segmentMask
final int segmentMaskMask value for indexing into segments. The upper bits of a key's hash code are used to choose the segment. -
segmentShift
final int segmentShiftShift value for indexing within segments. Helps prevent entries that end up in the same segment from also ending up in the same bucket. -
segments
The segments, each of which is a specialized hash table. -
concurrencyLevel
final int concurrencyLevelThe concurrency level. -
keyEquivalence
Strategy for comparing keys. -
valueEquivalence
Strategy for comparing values. -
keyStrength
Strategy for referencing keys. -
valueStrength
Strategy for referencing values. -
maxWeight
final long maxWeightThe maximum weight of this map. UNSET_INT if there is no maximum. -
weigher
Weigher to weigh cache entries. -
expireAfterAccessNanos
final long expireAfterAccessNanosHow long after the last access to an entry the map will retain that entry. -
expireAfterWriteNanos
final long expireAfterWriteNanosHow long after the last write to an entry the map will retain that entry. -
refreshNanos
final long refreshNanosHow long after the last write an entry becomes a candidate for refresh. -
removalNotificationQueue
Entries waiting to be consumed by the removal listener. -
removalListener
A listener that is invoked when an entry is removed due to expiration or garbage collection of soft/weak entries. -
ticker
Measures time in a testable way. -
entryFactory
Factory used to create new entries. -
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
The default cache loader to use on loading operations. -
UNSET
Placeholder. Indicates that the value hasn't been set yet. -
DISCARDING_QUEUE
-
keySet
-
values
-
entrySet
-
-
Constructor Details
-
LocalCache
LocalCache(CacheBuilder<? super K, ? super V> builder, @CheckForNull CacheLoader<? super K, V> loader) Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
-
-
Method Details
-
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
Singleton placeholder that indicates a value is being loaded. -
nullEntry
-
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
This method is a convenience for testing. Code should callLocalCache.Segment.newEntry(K, int, com.google.common.cache.ReferenceEntry<K, V>)
directly. -
copyEntry
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
This method is a convenience for testing. Code should callLocalCache.Segment.setValue(com.google.common.cache.ReferenceEntry<K, V>, K, V, long)
instead. -
hash
-
reclaimValue
-
reclaimKey
-
isLive
This method is a convenience for testing. Code should callLocalCache.Segment.getLiveValue(com.google.common.cache.ReferenceEntry<K, V>, long)
instead. -
segmentFor
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
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 clean up stale entries. As such it should only be called outside a segment context, such as during iteration. -
isExpired
Returns true if the entry has expired. -
connectAccessOrder
-
nullifyAccessOrder
-
connectWriteOrder
-
nullifyWriteOrder
-
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
-
cleanUp
public void cleanUp() -
isEmpty
public boolean isEmpty() -
longSize
long longSize() -
size
public int size() -
get
-
get
- Throws:
ExecutionException
-
getIfPresent
-
getOrDefault
- Specified by:
getOrDefault
in interfaceConcurrentMap<K,
V> - Specified by:
getOrDefault
in interfaceMap<K,
V>
-
getOrLoad
- Throws:
ExecutionException
-
getAllPresent
-
getAll
- Throws:
ExecutionException
-
loadAll
@CheckForNull Map<K,V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader) throws ExecutionExceptionReturns the result of callingCacheLoader.loadAll(java.lang.Iterable<? extends K>)
, or null ifloader
doesn't implementloadAll
.- Throws:
ExecutionException
-
getEntry
Returns the internal entry for the specified key. The entry may be loading, expired, or partially collected. -
refresh
-
containsKey
- Specified by:
containsKey
in interfaceMap<K,
V> - Overrides:
containsKey
in classAbstractMap<K,
V>
-
containsValue
- Specified by:
containsValue
in interfaceMap<K,
V> - Overrides:
containsValue
in classAbstractMap<K,
V>
-
put
-
putIfAbsent
- Specified by:
putIfAbsent
in interfaceConcurrentMap<K,
V> - Specified by:
putIfAbsent
in interfaceMap<K,
V>
-
compute
-
computeIfAbsent
- Specified by:
computeIfAbsent
in interfaceConcurrentMap<K,
V> - Specified by:
computeIfAbsent
in interfaceMap<K,
V>
-
computeIfPresent
@CheckForNull public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> function) - Specified by:
computeIfPresent
in interfaceConcurrentMap<K,
V> - Specified by:
computeIfPresent
in interfaceMap<K,
V>
-
merge
-
putAll
-
remove
-
remove
-
replace
-
replace
-
clear
public void clear() -
invalidateAll
-
keySet
-
values
-
entrySet
-
removeIf
-