Created
June 5, 2014 17:42
-
-
Save DarkSeraphim/c57f2a75918ef475f23d to your computer and use it in GitHub Desktop.
simple LoadingCache implementation as seen with Guava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LoadingCache<K, V> extends HashMap<K, V> | |
{ | |
private final long timeout; | |
private final Function<K, V> function; | |
private Map<K, Long> timeouts = new HashMap<K, Long>(); | |
public LoadingCache(long timeout, Function<K, V> function) | |
{ | |
this.timeout = timeout; | |
this.function = function; | |
} | |
private boolean validate(K key) | |
{ | |
final long now = System.currentTimeMillis(); | |
Long l = this.timeouts.get(key); | |
if(l == null || l < now) | |
{ | |
return false; | |
} | |
return true; | |
} | |
@Override | |
public V get(K key) | |
{ | |
V val; | |
boolean invalid = !validate(); | |
if(invalid || !super.containsKey(key)) | |
{ | |
// Reset the lifespan | |
this.timeouts.put(System.currentTimeMillis() + this.timeout); | |
val = this.function.compute(key); | |
super.put(key, val); | |
} | |
else | |
val = super.get(key); | |
return val; | |
} | |
@Override | |
public V put(K key, V val) | |
{ | |
throw new UnsupportedOperationException("Use get(K key)"); | |
} | |
@Override | |
public void putAll(Map<K, V> map) | |
{ | |
throw new UnsupportedOperationException("Use get(K key)"); | |
} | |
} | |
public interface Function<K, V> | |
{ | |
public V compute(K key); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment