Class LocalCache.Segment<K,​V>

  • All Implemented Interfaces:
    java.io.Serializable, java.util.concurrent.locks.Lock
    Enclosing class:
    LocalCache<K,​V>

    static class LocalCache.Segment<K,​V>
    extends java.util.concurrent.locks.ReentrantLock
    Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock opportunistically, just to simplify some locking and avoid separate construction.
    • Field Detail

      • count

        volatile int count
        The number of live elements in this segment's region.
      • totalWeight

        long totalWeight
        The weight of the live elements in this segment's region.
      • modCount

        int modCount
        Number 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 threshold
        The table is expanded when its size exceeds this threshold. (The value of this field is always (int) (capacity * 0.75).)
      • table

        volatile java.util.concurrent.atomic.AtomicReferenceArray<ReferenceEntry<K,​V>> table
        The per-segment table.
      • maxSegmentWeight

        final long maxSegmentWeight
        The maximum weight of this segment. UNSET_INT if there is no maximum.
      • keyReferenceQueue

        final java.lang.ref.ReferenceQueue<K> keyReferenceQueue
        The key reference queue contains entries whose keys have been garbage collected, and which need to be cleaned up internally.
      • valueReferenceQueue

        final java.lang.ref.ReferenceQueue<V> valueReferenceQueue
        The value reference queue contains value references whose values have been garbage collected, and which need to be cleaned up internally.
      • recencyQueue

        final java.util.Queue<ReferenceEntry<K,​V>> 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

        final java.util.concurrent.atomic.AtomicInteger readCount
        A counter of the number of reads since the last write, used to drain queues on a small fraction of read operations.
      • writeQueue

        final java.util.Queue<ReferenceEntry<K,​V>> 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

        final java.util.Queue<ReferenceEntry<K,​V>> 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).
    • Method Detail

      • newEntryArray

        java.util.concurrent.atomic.AtomicReferenceArray<ReferenceEntry<K,​V>> newEntryArray​(int size)
      • initTable

        void initTable​(java.util.concurrent.atomic.AtomicReferenceArray<ReferenceEntry<K,​V>> newTable)
      • copyEntry

        ReferenceEntry<K,​V> copyEntry​(ReferenceEntry<K,​V> original,
                                            ReferenceEntry<K,​V> newNext)
        Copies original into a new entry chained to newNext. Returns the new entry, or null if original was already garbage collected.
      • setValue

        void setValue​(ReferenceEntry<K,​V> entry,
                      K key,
                      V value,
                      long now)
        Sets a new value of an entry. Adds newly created entries at the end of the access queue.
      • get

        V get​(K key,
              int hash,
              CacheLoader<? super K,​V> loader)
        throws java.util.concurrent.ExecutionException
        Throws:
        java.util.concurrent.ExecutionException
      • get

        V get​(java.lang.Object key,
              int hash)
      • lockedGetOrLoad

        V lockedGetOrLoad​(K key,
                          int hash,
                          CacheLoader<? super K,​V> loader)
                   throws java.util.concurrent.ExecutionException
        Throws:
        java.util.concurrent.ExecutionException
      • waitForLoadingValue

        V waitForLoadingValue​(ReferenceEntry<K,​V> e,
                              K key,
                              LocalCache.ValueReference<K,​V> valueReference)
                       throws java.util.concurrent.ExecutionException
        Throws:
        java.util.concurrent.ExecutionException
      • compute

        V compute​(K key,
                  int hash,
                  java.util.function.BiFunction<? super K,​? super V,​? extends V> function)
      • getAndRecordStats

        V getAndRecordStats​(K key,
                            int hash,
                            LocalCache.LoadingValueReference<K,​V> loadingValueReference,
                            ListenableFuture<V> newValue)
                     throws java.util.concurrent.ExecutionException
        Waits uninterruptibly for newValue to be loaded, and then records loading stats.
        Throws:
        java.util.concurrent.ExecutionException
      • refresh

        V refresh​(K key,
                  int hash,
                  CacheLoader<? super K,​V> loader,
                  boolean checkTime)
        Refreshes the value associated with key, unless another thread is already doing so. Returns the newly refreshed value associated with key if it was refreshed inline, or null if another thread is performing the refresh or if an error occurs during refresh.
      • insertLoadingValueReference

        LocalCache.LoadingValueReference<K,​V> insertLoadingValueReference​(K key,
                                                                                int hash,
                                                                                boolean checkTime)
        Returns a newly inserted LoadingValueReference, 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()
      • recordLockedRead

        void recordLockedRead​(ReferenceEntry<K,​V> entry,
                              long now)
        Updates the eviction metadata that entry was just read. This currently amounts to adding entry 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

        void recordWrite​(ReferenceEntry<K,​V> entry,
                         int weight,
                         long now)
        Updates eviction metadata that entry was just written. This currently amounts to adding entry 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​(K key,
                                 int hash,
                                 V value,
                                 int weight,
                                 RemovalCause cause)
      • evictEntries

        void evictEntries​(ReferenceEntry<K,​V> newest)
        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
      • getFirst

        ReferenceEntry<K,​V> getFirst​(int hash)
        Returns first entry of bin for given hash.
      • getEntry

        ReferenceEntry<K,​V> getEntry​(java.lang.Object key,
                                           int hash)
      • getLiveEntry

        ReferenceEntry<K,​V> getLiveEntry​(java.lang.Object key,
                                               int hash,
                                               long now)
      • 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.
      • containsKey

        boolean containsKey​(java.lang.Object key,
                            int hash)
      • put

        V put​(K key,
              int hash,
              V value,
              boolean onlyIfAbsent)
      • expand

        void expand()
        Expands the table if possible.
      • replace

        boolean replace​(K key,
                        int hash,
                        V oldValue,
                        V newValue)
      • replace

        V replace​(K key,
                  int hash,
                  V newValue)
      • remove

        V remove​(java.lang.Object key,
                 int hash)
      • remove

        boolean remove​(java.lang.Object key,
                       int hash,
                       java.lang.Object value)
      • clear

        void clear()
      • removeCollectedEntry

        void removeCollectedEntry​(ReferenceEntry<K,​V> entry)
      • reclaimKey

        boolean reclaimKey​(ReferenceEntry<K,​V> entry,
                           int hash)
        Removes an entry whose key has been garbage collected.
      • reclaimValue

        boolean reclaimValue​(K key,
                             int hash,
                             LocalCache.ValueReference<K,​V> valueReference)
        Removes an entry whose value has been garbage collected.
      • 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()