1 package io.branch.rnbranch; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 6 /** 7 * Created by jdee on 3/8/17. 8 */ 9 10 public class AgingHash<KeyType, ValueType> { 11 private long mTtlMillis; 12 private HashMap<KeyType, AgingItem<ValueType>> mHash = new HashMap<>(); 13 AgingHash(long ttlMillis)14 public AgingHash(long ttlMillis) { 15 mTtlMillis = ttlMillis; 16 } 17 getTtlMillis()18 public long getTtlMillis() { 19 return mTtlMillis; 20 } 21 put(KeyType key, ValueType value)22 public void put(KeyType key, ValueType value) { 23 ageItems(); 24 25 AgingItem<ValueType> item = new AgingItem<>(value); 26 mHash.put(key, item); 27 } 28 get(KeyType key)29 public ValueType get(KeyType key) { 30 AgingItem<ValueType> item = mHash.get(key); 31 if (item == null) return null; 32 33 return item.get(); 34 } 35 remove(KeyType key)36 public void remove(KeyType key) { 37 mHash.remove(key); 38 } 39 ageItems()40 private void ageItems() { 41 long now = System.currentTimeMillis(); 42 43 Iterator it = mHash.entrySet().iterator(); 44 while (it.hasNext()) { 45 HashMap.Entry pair = (HashMap.Entry) it.next(); 46 AgingItem<ValueType> item = (AgingItem<ValueType>) pair.getValue(); 47 if (now - item.getAccessTime() >= mTtlMillis) { 48 it.remove(); 49 } 50 } 51 } 52 } 53