Blossomforth

HashCache

Mar 19th, 2016
277
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. package me.corriekay.simplymodular.util;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. import com.google.common.collect.MapMaker;
  7. import com.google.inject.Provider;
  8.  
  9. /**
  10.  * HashCache is a cache designed to store both strong and weak references to objects. This is designed to help with data concurrency.
  11.  * @author Corrie
  12.  */
  13. public class HashCache<K, V> {
  14.     private final Map<K, V> map = new HashMap<>();
  15.     private final Map<K, V> cache = new MapMaker().weakValues().makeMap();
  16.    
  17.     public V get(K k) {
  18.         if(cache.containsKey(k)) return cache.get(k);
  19.         return map.get(k);
  20.     }
  21.    
  22.     public V optGet(K k, Provider<V> p) {
  23.         V v = get(k);
  24.         if(v == null) {
  25.             v = p.get();
  26.             cache.put(k, v);
  27.         }
  28.         return v;
  29.     }
  30.    
  31.     public void put(K k, Provider<V> p) {
  32.         if(!cache.containsKey(k)) {
  33.             V v = p.get();
  34.             cache.put(k, v);
  35.             map.put(k, v);
  36.         } else {
  37.             map.put(k, cache.get(k));
  38.         }
  39.     }
  40.    
  41.     public void remove(K k) {
  42.         map.remove(k);
  43.     }
  44.    
  45.     public void hardRemove(K k) {
  46.         remove(k);
  47.         cache.remove(k);
  48.     }
  49. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment