Class ConcurrentCache<K,​V>

  • All Implemented Interfaces:
    Cache

    public class ConcurrentCache<K,​V>
    extends AbstractCache
    Concurrent cache implementation that uses cache segments to minimize the chance of lock contention. The LRU algorithm is used to evict excess entries from each cache segment separately, which makes the combined eviction algorithm similar but not exactly the same as LRU. None of the methods of this class are synchronized, but they are all thread-safe.
    • Constructor Detail

      • ConcurrentCache

        public ConcurrentCache​(String name,
                               int numberOfSegments)
      • ConcurrentCache

        public ConcurrentCache​(String name)
    • Method Detail

      • containsKey

        public boolean containsKey​(K key)
        Checks if the identified entry is cached.
        Parameters:
        key - entry key
        Returns:
        true if the entry is cached, false otherwise
      • get

        public V get​(K key)
        Returns the identified cache entry.
        Parameters:
        key - entry key
        Returns:
        entry value, or null if not found
      • values

        public List<V> values()
        Returns all values in the cache. Note that this method is not synchronized over the entire cache, so it is only guaranteed to return accurate results when there are no concurrent threads modifying the cache.
        Returns:
        cached values
      • put

        public V put​(K key,
                     V value,
                     long size)
        Adds the given entry to the cache.
        Parameters:
        key - entry key
        value - entry value
        size - entry size
        Returns:
        the previous value, or null
      • remove

        public V remove​(K key)
        Removes the identified entry from the cache.
        Parameters:
        key - entry key
        Returns:
        removed entry, or null if not found
      • clear

        public void clear()
        Clears all segments of the cache. Note that even this method is not synchronized over the entire cache, so it needs to explicitly count the cache size changes and may return with a non-empty cache if other threads have concurrently been adding new entries.
      • isEmpty

        public boolean isEmpty()
        Checks if the cache size is zero.
      • setMaxMemorySize

        public void setMaxMemorySize​(long size)
        Sets the maximum size of the cache and evicts any excess items until the current size falls within the given limit.
        Specified by:
        setMaxMemorySize in interface Cache
        Overrides:
        setMaxMemorySize in class AbstractCache
        Parameters:
        size - the size in bytes
      • getElementCount

        public long getElementCount()
        Description copied from interface: Cache
        Get the number of elements/objects in the cache.
        Returns:
        the number of elements