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) class
LocalCache.AbstractCacheSet<T>
(package private) static class
LocalCache.AbstractReferenceEntry<K,V>
(package private) static class
LocalCache.AccessQueue<K,V>
A custom queue for managing access order.(package private) static class
LocalCache.ComputingValueReference<K,V>
(package private) static class
LocalCache.EntryFactory
Creates new entries.(package private) class
LocalCache.EntryIterator
(package private) class
LocalCache.EntrySet
(package private) class
LocalCache.HashIterator<T>
(package private) class
LocalCache.KeyIterator
(package private) class
LocalCache.KeySet
(package private) static class
LocalCache.LoadingSerializationProxy<K,V>
Serializes the configuration of a LocalCache, reconstituting it as an LoadingCache using CacheBuilder upon deserialization.(package private) static class
LocalCache.LoadingValueReference<K,V>
(package private) static class
LocalCache.LocalLoadingCache<K,V>
(package private) static class
LocalCache.LocalManualCache<K,V>
(package private) static class
LocalCache.ManualSerializationProxy<K,V>
Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder upon deserialization.private static class
LocalCache.NullEntry
(package private) static class
LocalCache.Segment<K,V>
Segments are specialized versions of hash tables.(package private) static class
LocalCache.SoftValueReference<K,V>
References a soft value.(package private) static class
LocalCache.Strength
(package private) static class
LocalCache.StrongAccessEntry<K,V>
(package private) static class
LocalCache.StrongAccessWriteEntry<K,V>
(package private) static class
LocalCache.StrongEntry<K,V>
Used for strongly-referenced keys.(package private) static class
LocalCache.StrongValueReference<K,V>
References a strong value.(package private) static class
LocalCache.StrongWriteEntry<K,V>
(package private) class
LocalCache.ValueIterator
(package private) static interface
LocalCache.ValueReference<K,V>
A reference to a value.(package private) class
LocalCache.Values
(package private) static class
LocalCache.WeakAccessEntry<K,V>
(package private) static class
LocalCache.WeakAccessWriteEntry<K,V>
(package private) static class
LocalCache.WeakEntry<K,V>
Used for weakly-referenced keys.(package private) static class
LocalCache.WeakValueReference<K,V>
References a weak value.(package private) static class
LocalCache.WeakWriteEntry<K,V>
(package private) static class
LocalCache.WeightedSoftValueReference<K,V>
References a soft value.(package private) static class
LocalCache.WeightedStrongValueReference<K,V>
References a strong value.(package private) static class
LocalCache.WeightedWeakValueReference<K,V>
References a weak value.(package private) static class
LocalCache.WriteQueue<K,V>
A custom queue for managing eviction order.(package private) class
LocalCache.WriteThroughEntry
Custom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying map.
-
Field Summary
Fields Modifier and Type Field Description (package private) int
concurrencyLevel
The concurrency level.(package private) static int
CONTAINS_VALUE_RETRIES
Number of (unsynchronized) retries in the containsValue method.(package private) CacheLoader<? super K,V>
defaultLoader
The default cache loader to use on loading operations.(package private) static java.util.Queue<?>
DISCARDING_QUEUE
(package private) static int
DRAIN_MAX
Maximum number of entries to be drained in a single cleanup run.(package private) static int
DRAIN_THRESHOLD
Number of cache access operations that can be buffered per segment before the cache's recency ordering information is updated.(package private) LocalCache.EntryFactory
entryFactory
Factory used to create new entries.(package private) java.util.Set<java.util.Map.Entry<K,V>>
entrySet
(package private) long
expireAfterAccessNanos
How long after the last access to an entry the map will retain that entry.(package private) long
expireAfterWriteNanos
How long after the last write to an entry the map will retain that entry.(package private) AbstractCache.StatsCounter
globalStatsCounter
Accumulates global cache statistics.(package private) Equivalence<java.lang.Object>
keyEquivalence
Strategy for comparing keys.(package private) java.util.Set<K>
keySet
(package private) LocalCache.Strength
keyStrength
Strategy for referencing keys.(package private) static java.util.logging.Logger
logger
(package private) static int
MAX_SEGMENTS
The maximum number of segments to allow; used to bound constructor arguments.(package private) static int
MAXIMUM_CAPACITY
The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments.(package private) long
maxWeight
The maximum weight of this map.(package private) long
refreshNanos
How long after the last write an entry becomes a candidate for refresh.(package private) RemovalListener<K,V>
removalListener
A 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>>
removalNotificationQueue
Entries waiting to be consumed by the removal listener.(package private) int
segmentMask
Mask value for indexing into segments.(package private) LocalCache.Segment<K,V>[]
segments
The segments, each of which is a specialized hash table.(package private) int
segmentShift
Shift value for indexing within segments.(package private) Ticker
ticker
Measures time in a testable way.(package private) static LocalCache.ValueReference<java.lang.Object,java.lang.Object>
UNSET
Placeholder.(package private) Equivalence<java.lang.Object>
valueEquivalence
Strategy for comparing values.(package private) java.util.Collection<V>
values
(package private) LocalCache.Strength
valueStrength
Strategy for referencing values.(package private) Weigher<K,V>
weigher
Weigher 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 void
cleanUp()
void
clear()
V
compute(K key, java.util.function.BiFunction<? super K,? super V,? extends V> function)
V
computeIfAbsent(K key, java.util.function.Function<? super K,? extends V> function)
V
computeIfPresent(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)
boolean
containsKey(java.lang.Object key)
boolean
containsValue(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) boolean
customWeigher()
(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) boolean
evictsBySize()
(package private) boolean
expires()
(package private) boolean
expiresAfterAccess()
(package private) boolean
expiresAfterWrite()
V
get(java.lang.Object key)
(package private) V
get(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.V
getIfPresent(java.lang.Object key)
(package private) V
getLiveValue(ReferenceEntry<K,V> entry, long now)
Gets the value from an entry.V
getOrDefault(java.lang.Object key, V defaultValue)
(package private) V
getOrLoad(K key)
(package private) int
hash(java.lang.Object key)
(package private) void
invalidateAll(java.lang.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.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 ifloader
doesn't implementloadAll
.(package private) long
longSize()
V
merge(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) void
processPendingNotifications()
Notifies listeners that an entry has been automatically removed due to expiration, eviction, or eligibility for garbage collection.V
put(K key, V value)
void
putAll(java.util.Map<? extends K,? extends V> m)
V
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
recordsAccess()
(package private) boolean
recordsTime()
(package private) boolean
recordsWrite()
(package private) void
refresh(K key)
(package private) boolean
refreshes()
(package private) static int
rehash(int h)
Applies a supplemental hash function to a given hash code, which defends against poor quality hash functions.V
remove(java.lang.Object key)
boolean
remove(java.lang.Object key, java.lang.Object value)
(package private) boolean
removeIf(java.util.function.BiPredicate<? super K,? super V> filter)
V
replace(K key, V value)
boolean
replace(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.int
size()
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) boolean
usesAccessEntries()
(package private) boolean
usesAccessQueue()
(package private) boolean
usesKeyReferences()
(package private) boolean
usesValueReferences()
(package private) boolean
usesWriteEntries()
(package private) boolean
usesWriteQueue()
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<<30
to 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 ifloader
doesn'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)
-
-