Class LRUCache<K,V>

Object
LRUCache<K,V>
Type Parameters:
K - key-type used in the cache
V - value-type used in the cache

public class LRUCache<K,V> extends Object
A cache that discards items that haven't being used recently or frequently.

The discard strategy comes from Guava's size-based eviction's defaults.

See Guava Caches Explained.

It's thread-safe.

Author:
Owen Feehan
  • Constructor Summary

    Constructors
    Constructor
    Description
    LRUCache(int cacheSize, CheckedFunction<K,V,E> calculator)
    Constructor.
  • Method Summary

    Modifier and Type
    Method
    Description
    get(K key)
    Get a value, calculating if necessary, and caching the result.
    Gets an value, if present, but doesn't create any new entry if it's absent.
    boolean
    has(K key)
    Is a particular key present already in the cache?
    void
    put(K key, V value)
    Puts a key-value pair irrespective of whether its already present or not.
    long
    Number of items currently in the cache.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • LRUCache

      public LRUCache(int cacheSize, CheckedFunction<K,V,E> calculator)
      Constructor.
      Type Parameters:
      E - type of an exception that may be thrown by calculator.
      Parameters:
      cacheSize - maximum-size of cache.
      calculator - calculates the value for a given key if it's not already in the cache.
  • Method Details

    • get

      public V get(K key) throws GetOperationFailedException
      Get a value, calculating if necessary, and caching the result.
      Parameters:
      key - the key whose value will be either calculated freshly or retrieved from the cache.
      Returns:
      the value of applying calculator (see constructor argument) on value key.
      Throws:
      GetOperationFailedException - if the key doesn't exist.
    • has

      public boolean has(K key)
      Is a particular key present already in the cache?
      Parameters:
      key - they key to check.
      Returns:
      true iff the key already exists in the cache.
    • sizeCurrentLoad

      public long sizeCurrentLoad()
      Number of items currently in the cache.
      Returns:
      the number of items.
    • getIfPresent

      public Optional<V> getIfPresent(K key)
      Gets an value, if present, but doesn't create any new entry if it's absent.
      Parameters:
      key - the key.
      Returns:
      an existing element if present or Optional.empty() otherwise.
    • put

      public void put(K key, V value)
      Puts a key-value pair irrespective of whether its already present or not.
      Parameters:
      key - the key.
      value - the value.