Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package reghzy.api.utils;
- /**
- * A helper class for caching map entries. This is only really intended to be used if the map isn't modified often
- * @param <K> The key
- * @param <V> The value
- */
- public abstract class KVObjectCache<K, V> {
- private K lastAccessedKey;
- private V lastAccessedValue;
- /**
- * 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)}
- * @param key
- * @return
- */
- public V get(K key) {
- K thisKey = this.lastAccessedKey;
- V value;
- if (key == thisKey) {
- if ((value = this.lastAccessedValue) == null) {
- return this.lastAccessedValue = getValue(key);
- }
- return value;
- }
- else if (key == null) {
- this.lastAccessedKey = null;
- return this.lastAccessedValue = getValue(null);
- }
- else if (key.equals(thisKey)) {
- this.lastAccessedKey = key;
- if ((value = this.lastAccessedValue) == null) {
- return this.lastAccessedValue = getValue(key);
- }
- return value;
- }
- else {
- this.lastAccessedKey = key;
- return this.lastAccessedValue = getValue(key);
- }
- }
- /**
- * An abstract method for getting the value from a key
- * @param key The key
- * @return The value
- */
- public abstract V getValue(K key);
- /**
- * Clears the cached key and value
- */
- public void clear() {
- this.lastAccessedKey = null;
- this.lastAccessedValue = null;
- }
- /**
- * Invalidates the currently held cached object, if the given key matches this cache's key
- */
- public void invalidate(K key) {
- K thisKey = this.lastAccessedKey;
- if (key == thisKey) {
- this.lastAccessedKey = null;
- }
- else if (key != null && key.equals(thisKey)) {
- this.lastAccessedKey = null;
- }
- }
- }
Add Comment
Please, Sign In to add comment