Package com.google.common.cache
Class LocalCache.Segment<K,V>
java.lang.Object
java.util.concurrent.locks.ReentrantLock
com.google.common.cache.LocalCache.Segment<K,V>
- All Implemented Interfaces:
Serializable,Lock
- Enclosing class:
- LocalCache<K,
V>
Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock
opportunistically, just to simplify some locking and avoid separate construction.
-
Field Summary
FieldsModifier and TypeFieldDescription(package private) final Queue<ReferenceEntry<K,V>> A queue of elements currently in the map, ordered by access time.(package private) intThe number of live elements in this segment's region.(package private) final ReferenceQueue<K>The key reference queue contains entries whose keys have been garbage collected, and which need to be cleaned up internally.(package private) final LocalCache<K,V> (package private) final longThe maximum weight of this segment.(package private) intNumber of updates that alter the size of the table.(package private) final AtomicIntegerA counter of the number of reads since the last write, used to drain queues on a small fraction of read operations.(package private) final Queue<ReferenceEntry<K,V>> The recency queue is used to record which entries were accessed for updating the access list's ordering.(package private) final AbstractCache.StatsCounterAccumulates cache statistics.(package private) AtomicReferenceArray<ReferenceEntry<K,V>> The per-segment table.(package private) intThe table is expanded when its size exceeds this threshold.(package private) longThe weight of the live elements in this segment's region.(package private) final ReferenceQueue<V>The value reference queue contains value references whose values have been garbage collected, and which need to be cleaned up internally.(package private) final Queue<ReferenceEntry<K,V>> A queue of elements currently in the map, ordered by write time. -
Constructor Summary
ConstructorsConstructorDescriptionSegment(LocalCache<K, V> map, int initialCapacity, long maxSegmentWeight, AbstractCache.StatsCounter statsCounter) -
Method Summary
Modifier and TypeMethodDescription(package private) voidcleanUp()(package private) voidclear()(package private) void(package private) voidClears all entries from the key and value reference queues.(package private) void(package private) V(package private) booleancontainsKey(Object key, int hash) (package private) booleancontainsValue(Object value) This method is a convenience for testing.(package private) ReferenceEntry<K,V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) Copiesoriginalinto a new entry chained tonewNext.(package private) void(package private) voidDrains the recency queue, updating eviction metadata that the entries therein were read in the specified relative order.(package private) voidDrain the key and value reference queues, cleaning up internal entries containing garbage collected keys or values.(package private) void(package private) voidenqueueNotification(K key, int hash, V value, int weight, RemovalCause cause) (package private) voidevictEntries(ReferenceEntry<K, V> newest) Performs eviction if the segment is over capacity.(package private) voidexpand()Expands the table if possible.(package private) voidexpireEntries(long now) (package private) V(package private) Vget(K key, int hash, CacheLoader<? super K, V> loader) (package private) VgetAndRecordStats(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, ListenableFuture<V> newValue) Waits uninterruptibly fornewValueto be loaded, and then records loading stats.(package private) ReferenceEntry<K,V> (package private) ReferenceEntry<K,V> getFirst(int hash) Returns first entry of bin for given hash.(package private) ReferenceEntry<K,V> getLiveEntry(Object key, int hash, long now) (package private) VgetLiveValue(ReferenceEntry<K, V> entry, long now) Gets the value from an entry.(package private) ReferenceEntry<K,V> (package private) voidinitTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) (package private) LocalCache.LoadingValueReference<K,V> insertLoadingValueReference(K key, int hash, boolean checkTime) Returns a newly insertedLoadingValueReference, or null if the live value reference is already loading.(package private) ListenableFuture<V>loadAsync(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) (package private) VloadSync(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) (package private) VlockedGetOrLoad(K key, int hash, CacheLoader<? super K, V> loader) (package private) ReferenceEntry<K,V> newEntry(K key, int hash, ReferenceEntry<K, V> next) (package private) AtomicReferenceArray<ReferenceEntry<K,V>> newEntryArray(int size) (package private) voidPerforms routine cleanup following a read.(package private) voidPerforms routine cleanup following a write.(package private) voidpreWriteCleanup(long now) Performs routine cleanup prior to executing a write.(package private) V(package private) booleanreclaimKey(ReferenceEntry<K, V> entry, int hash) Removes an entry whose key has been garbage collected.(package private) booleanreclaimValue(K key, int hash, LocalCache.ValueReference<K, V> valueReference) Removes an entry whose value has been garbage collected.(package private) voidrecordLockedRead(ReferenceEntry<K, V> entry, long now) Updates the eviction metadata thatentrywas just read.(package private) voidrecordRead(ReferenceEntry<K, V> entry, long now) Records the relative order in which this read was performed by addingentryto the recency queue.(package private) voidrecordWrite(ReferenceEntry<K, V> entry, int weight, long now) Updates eviction metadata thatentrywas just written.(package private) Vrefresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) Refreshes the value associated withkey, unless another thread is already doing so.(package private) V(package private) boolean(package private) voidremoveCollectedEntry(ReferenceEntry<K, V> entry) (package private) booleanremoveEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) (package private) ReferenceEntry<K,V> removeEntryFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) (package private) booleanremoveLoadingValue(K key, int hash, LocalCache.LoadingValueReference<K, V> valueReference) (package private) ReferenceEntry<K,V> removeValueFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry, K key, int hash, V value, LocalCache.ValueReference<K, V> valueReference, RemovalCause cause) (package private) V(package private) boolean(package private) voidrunLockedCleanup(long now) (package private) void(package private) VscheduleRefresh(ReferenceEntry<K, V> entry, K key, int hash, V oldValue, long now, CacheLoader<? super K, V> loader) (package private) voidSets a new value of an entry.(package private) booleanstoreLoadedValue(K key, int hash, LocalCache.LoadingValueReference<K, V> oldValueReference, V newValue) (package private) voidCleanup collected entries when the lock is available.(package private) voidtryExpireEntries(long now) Cleanup expired entries when the lock is available.(package private) VwaitForLoadingValue(ReferenceEntry<K, V> e, K key, LocalCache.ValueReference<K, V> valueReference) Methods inherited from class java.util.concurrent.locks.ReentrantLock
getHoldCount, getOwner, getQueuedThreads, getQueueLength, getWaitingThreads, getWaitQueueLength, hasQueuedThread, hasQueuedThreads, hasWaiters, isFair, isHeldByCurrentThread, isLocked, lock, lockInterruptibly, newCondition, toString, tryLock, tryLock, unlock
-
Field Details
-
map
-
count
volatile int countThe number of live elements in this segment's region. -
totalWeight
long totalWeightThe weight of the live elements in this segment's region. -
modCount
int modCountNumber of updates that alter the size of the table. This is used during bulk-read methods to make sure they see a consistent snapshot: If modCounts change during a traversal of segments loading size or checking containsValue, then we might have an inconsistent view of state so (usually) must retry. -
threshold
int thresholdThe table is expanded when its size exceeds this threshold. (The value of this field is always(int) (capacity * 0.75).) -
table
The per-segment table. -
maxSegmentWeight
final long maxSegmentWeightThe maximum weight of this segment. UNSET_INT if there is no maximum. -
keyReferenceQueue
The key reference queue contains entries whose keys have been garbage collected, and which need to be cleaned up internally. -
valueReferenceQueue
The value reference queue contains value references whose values have been garbage collected, and which need to be cleaned up internally. -
recencyQueue
The recency queue is used to record which entries were accessed for updating the access list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is crossed or a write occurs on the segment. -
readCount
A counter of the number of reads since the last write, used to drain queues on a small fraction of read operations. -
writeQueue
A queue of elements currently in the map, ordered by write time. Elements are added to the tail of the queue on write. -
accessQueue
A queue of elements currently in the map, ordered by access time. Elements are added to the tail of the queue on access (note that writes count as accesses). -
statsCounter
Accumulates cache statistics.
-
-
Constructor Details
-
Segment
Segment(LocalCache<K, V> map, int initialCapacity, long maxSegmentWeight, AbstractCache.StatsCounter statsCounter)
-
-
Method Details
-
newEntryArray
-
initTable
-
newEntry
-
copyEntry
@CheckForNull ReferenceEntry<K,V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) Copiesoriginalinto a new entry chained tonewNext. Returns the new entry, ornulliforiginalwas already garbage collected. -
setValue
Sets a new value of an entry. Adds newly created entries at the end of the access queue. -
get
- Throws:
ExecutionException
-
get
-
lockedGetOrLoad
- Throws:
ExecutionException
-
waitForLoadingValue
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, LocalCache.ValueReference<K, throws ExecutionExceptionV> valueReference) - Throws:
ExecutionException
-
compute
-
loadSync
V loadSync(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, throws ExecutionExceptionV> loader) - Throws:
ExecutionException
-
loadAsync
ListenableFuture<V> loadAsync(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) -
getAndRecordStats
V getAndRecordStats(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, ListenableFuture<V> newValue) throws ExecutionExceptionWaits uninterruptibly fornewValueto be loaded, and then records loading stats.- Throws:
ExecutionException
-
scheduleRefresh
V scheduleRefresh(ReferenceEntry<K, V> entry, K key, int hash, V oldValue, long now, CacheLoader<? super K, V> loader) -
refresh
Refreshes the value associated withkey, unless another thread is already doing so. Returns the newly refreshed value associated withkeyif it was refreshed inline, ornullif another thread is performing the refresh or if an error occurs during refresh. -
insertLoadingValueReference
@CheckForNull LocalCache.LoadingValueReference<K,V> insertLoadingValueReference(K key, int hash, boolean checkTime) Returns a newly insertedLoadingValueReference, or null if the live value reference is already loading. -
tryDrainReferenceQueues
void tryDrainReferenceQueues()Cleanup collected entries when the lock is available. -
drainReferenceQueues
void drainReferenceQueues()Drain the key and value reference queues, cleaning up internal entries containing garbage collected keys or values. -
drainKeyReferenceQueue
void drainKeyReferenceQueue() -
drainValueReferenceQueue
void drainValueReferenceQueue() -
clearReferenceQueues
void clearReferenceQueues()Clears all entries from the key and value reference queues. -
clearKeyReferenceQueue
void clearKeyReferenceQueue() -
clearValueReferenceQueue
void clearValueReferenceQueue() -
recordRead
Records the relative order in which this read was performed by addingentryto the recency queue. At write-time, or when the queue is full past the threshold, the queue will be drained and the entries therein processed.Note: locked reads should use
recordLockedRead(com.google.common.cache.ReferenceEntry<K, V>, long). -
recordLockedRead
Updates the eviction metadata thatentrywas just read. This currently amounts to addingentryto relevant eviction lists.Note: this method should only be called under lock, as it directly manipulates the eviction queues. Unlocked reads should use
recordRead(com.google.common.cache.ReferenceEntry<K, V>, long). -
recordWrite
Updates eviction metadata thatentrywas just written. This currently amounts to addingentryto relevant eviction lists. -
drainRecencyQueue
void drainRecencyQueue()Drains the recency queue, updating eviction metadata that the entries therein were read in the specified relative order. This currently amounts to adding them to relevant eviction lists (accounting for the fact that they could have been removed from the map since being added to the recency queue). -
tryExpireEntries
void tryExpireEntries(long now) Cleanup expired entries when the lock is available. -
expireEntries
void expireEntries(long now) -
enqueueNotification
void enqueueNotification(@CheckForNull K key, int hash, @CheckForNull V value, int weight, RemovalCause cause) -
evictEntries
Performs eviction if the segment is over capacity. Avoids flushing the entire cache if the newest entry exceeds the maximum weight all on its own.- Parameters:
newest- the most recently added entry
-
getNextEvictable
ReferenceEntry<K,V> getNextEvictable() -
getFirst
Returns first entry of bin for given hash. -
getEntry
-
getLiveEntry
-
getLiveValue
Gets the value from an entry. Returns null if the entry is invalid, partially-collected, loading, or expired. -
containsKey
-
containsValue
This method is a convenience for testing. Code should callLocalCache.containsValue(java.lang.Object)directly. -
put
-
expand
void expand()Expands the table if possible. -
replace
-
replace
-
remove
-
remove
-
storeLoadedValue
boolean storeLoadedValue(K key, int hash, LocalCache.LoadingValueReference<K, V> oldValueReference, V newValue) -
clear
void clear() -
removeValueFromChain
@CheckForNull ReferenceEntry<K,V> removeValueFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry, @CheckForNull K key, int hash, V value, LocalCache.ValueReference<K, V> valueReference, RemovalCause cause) -
removeEntryFromChain
@CheckForNull ReferenceEntry<K,V> removeEntryFromChain(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) -
removeCollectedEntry
-
reclaimKey
Removes an entry whose key has been garbage collected. -
reclaimValue
Removes an entry whose value has been garbage collected. -
removeLoadingValue
-
removeEntry
-
postReadCleanup
void postReadCleanup()Performs routine cleanup following a read. Normally cleanup happens during writes. If cleanup is not observed after a sufficient number of reads, try cleaning up from the read thread. -
preWriteCleanup
void preWriteCleanup(long now) Performs routine cleanup prior to executing a write. This should be called every time a write thread acquires the segment lock, immediately after acquiring the lock.Post-condition: expireEntries has been run.
-
postWriteCleanup
void postWriteCleanup()Performs routine cleanup following a write. -
cleanUp
void cleanUp() -
runLockedCleanup
void runLockedCleanup(long now) -
runUnlockedCleanup
void runUnlockedCleanup()
-