Skip to content

Instantly share code, notes, and snippets.

@ybonnel
Created May 26, 2014 12:33
Show Gist options
  • Save ybonnel/795a9f1ef0e08c9a585f to your computer and use it in GitHub Desktop.
Save ybonnel/795a9f1ef0e08c9a585f to your computer and use it in GitHub Desktop.
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public class SimpleCache<K, V> {
private final Function<K, V> initialValue;
private final ConcurrentHashMap<K, V> cache;
public SimpleCache(Function<K, V> initialValue) {
this.initialValue = initialValue;
cache = new ConcurrentHashMap<>();
}
public V get(K key) {
return cache.computeIfAbsent(key, initialValue);
}
}
public static void main(String[] args) {
SimpleCache<String, String> cache = new SimpleCache<>(key -> "Traitement long...");
String value = cache.get("key1");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment