bobmarley12345

java key/value cache v2

Nov 10th, 2021 (edited)
1,343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. package reghzy.api.utils;
  2.  
  3. /**
  4.  * A helper class for caching map entries. This is only really intended to be used if the map isn't modified often
  5.  * @param <K> The key
  6.  * @param <V> The value
  7.  */
  8. public abstract class KVObjectCache<K, V> {
  9.     private K lastAccessedKey;
  10.     private V lastAccessedValue;
  11.  
  12.     /**
  13.      * Gets the cached value if it isn't null, and the key is equal to this cache's cached key. Otherwise, it calls {@link KVObjectCache#getValue(Object)}
  14.      * @param key
  15.      * @return
  16.      */
  17.     public V get(K key) {
  18.         K thisKey = this.lastAccessedKey;
  19.         V value;
  20.         if (key == thisKey) {
  21.             if ((value = this.lastAccessedValue) == null) {
  22.                 return this.lastAccessedValue = getValue(key);
  23.             }
  24.  
  25.             return value;
  26.         }
  27.         else if (key == null) {
  28.             this.lastAccessedKey = null;
  29.             return this.lastAccessedValue = getValue(null);
  30.         }
  31.         else if (key.equals(thisKey)) {
  32.             this.lastAccessedKey = key;
  33.             if ((value = this.lastAccessedValue) == null) {
  34.                 return this.lastAccessedValue = getValue(key);
  35.             }
  36.  
  37.             return value;
  38.         }
  39.         else {
  40.             this.lastAccessedKey = key;
  41.             return this.lastAccessedValue = getValue(key);
  42.         }
  43.     }
  44.  
  45.     /**
  46.      * An abstract method for getting the value from a key
  47.      * @param key The key
  48.      * @return The value
  49.      */
  50.     public abstract V getValue(K key);
  51.  
  52.     /**
  53.      * Clears the cached key and value
  54.      */
  55.     public void clear() {
  56.         this.lastAccessedKey = null;
  57.         this.lastAccessedValue = null;
  58.     }
  59.  
  60.     /**
  61.      * Invalidates the currently held cached object, if the given key matches this cache's key
  62.      */
  63.     public void invalidate(K key) {
  64.         K thisKey = this.lastAccessedKey;
  65.         if (key == thisKey) {
  66.             this.lastAccessedKey = null;
  67.         }
  68.         else if (key != null && key.equals(thisKey)) {
  69.             this.lastAccessedKey = null;
  70.         }
  71.     }
  72. }
  73.  
Add Comment
Please, Sign In to add comment