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) int
The 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 long
The maximum weight of this segment.(package private) int
Number of updates that alter the size of the table.(package private) final AtomicInteger
A 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.StatsCounter
Accumulates cache statistics.(package private) AtomicReferenceArray
<ReferenceEntry<K, V>> The per-segment table.(package private) int
The table is expanded when its size exceeds this threshold.(package private) long
The 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) void
cleanUp()
(package private) void
clear()
(package private) void
(package private) void
Clears all entries from the key and value reference queues.(package private) void
(package private) V
(package private) boolean
containsKey
(Object key, int hash) (package private) boolean
containsValue
(Object value) This method is a convenience for testing.(package private) ReferenceEntry
<K, V> copyEntry
(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) Copiesoriginal
into a new entry chained tonewNext
.(package private) void
(package private) void
Drains the recency queue, updating eviction metadata that the entries therein were read in the specified relative order.(package private) void
Drain the key and value reference queues, cleaning up internal entries containing garbage collected keys or values.(package private) void
(package private) void
enqueueNotification
(K key, int hash, V value, int weight, RemovalCause cause) (package private) void
evictEntries
(ReferenceEntry<K, V> newest) Performs eviction if the segment is over capacity.(package private) void
expand()
Expands the table if possible.(package private) void
expireEntries
(long now) (package private) V
(package private) V
get
(K key, int hash, CacheLoader<? super K, V> loader) (package private) V
getAndRecordStats
(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, ListenableFuture<V> newValue) Waits uninterruptibly fornewValue
to 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) V
getLiveValue
(ReferenceEntry<K, V> entry, long now) Gets the value from an entry.(package private) ReferenceEntry
<K, V> (package private) void
initTable
(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) V
loadSync
(K key, int hash, LocalCache.LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) (package private) V
lockedGetOrLoad
(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) void
Performs routine cleanup following a read.(package private) void
Performs routine cleanup following a write.(package private) void
preWriteCleanup
(long now) Performs routine cleanup prior to executing a write.(package private) V
(package private) boolean
reclaimKey
(ReferenceEntry<K, V> entry, int hash) Removes an entry whose key has been garbage collected.(package private) boolean
reclaimValue
(K key, int hash, LocalCache.ValueReference<K, V> valueReference) Removes an entry whose value has been garbage collected.(package private) void
recordLockedRead
(ReferenceEntry<K, V> entry, long now) Updates the eviction metadata thatentry
was just read.(package private) void
recordRead
(ReferenceEntry<K, V> entry, long now) Records the relative order in which this read was performed by addingentry
to the recency queue.(package private) void
recordWrite
(ReferenceEntry<K, V> entry, int weight, long now) Updates eviction metadata thatentry
was just written.(package private) V
refresh
(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) void
removeCollectedEntry
(ReferenceEntry<K, V> entry) (package private) boolean
removeEntry
(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) (package private) ReferenceEntry
<K, V> removeEntryFromChain
(ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) (package private) boolean
removeLoadingValue
(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) void
runLockedCleanup
(long now) (package private) void
(package private) V
scheduleRefresh
(ReferenceEntry<K, V> entry, K key, int hash, V oldValue, long now, CacheLoader<? super K, V> loader) (package private) void
Sets a new value of an entry.(package private) boolean
storeLoadedValue
(K key, int hash, LocalCache.LoadingValueReference<K, V> oldValueReference, V newValue) (package private) void
Cleanup collected entries when the lock is available.(package private) void
tryExpireEntries
(long now) Cleanup expired entries when the lock is available.(package private) V
waitForLoadingValue
(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) Copiesoriginal
into a new entry chained tonewNext
. Returns the new entry, ornull
iforiginal
was 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 fornewValue
to 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 withkey
if it was refreshed inline, ornull
if 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 addingentry
to 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 thatentry
was just read. This currently amounts to addingentry
to 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 thatentry
was just written. This currently amounts to addingentry
to 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()
-