Skip to content

Instantly share code, notes, and snippets.

@shadowfacts
Created May 13, 2019 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadowfacts/043e39d27675e8f69eac360cfa40dea7 to your computer and use it in GitHub Desktop.
Save shadowfacts/043e39d27675e8f69eac360cfa40dea7 to your computer and use it in GitHub Desktop.
class ExpiringMap<K, V> extends HashMap<K, Entry<V>> {
class Entry<V> {
V value;
long expiry;
}
long decayTime = 60_000;
V get(K key) {
Entry<V> e = super.get(key);
if (System.currentTimeMillis() >= expiry) {
remove(key);
return null;
}
return e.value;
}
void put(K key, V value) {
super.put(key, new Entry<>(value, System.currentTimeMillis() + decayTime));
}
void refresh(K key) {
Entry<V> e = super.get(key);
e.expiry = System.currentTimeMillis() + decayTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment