Skip to content

Instantly share code, notes, and snippets.

@DarkSeraphim
Created June 5, 2014 17:42
Show Gist options
  • Save DarkSeraphim/c57f2a75918ef475f23d to your computer and use it in GitHub Desktop.
Save DarkSeraphim/c57f2a75918ef475f23d to your computer and use it in GitHub Desktop.
simple LoadingCache implementation as seen with Guava
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