最近在学习Hystrix框架时,看到有一段代码,挺有意思的,代码如下:
代码清单1-1
public class InternMap<K, V> {
private final ConcurrentMap<K, V> storage = new ConcurrentHashMap<K, V>();
private final ValueConstructor<K, V> valueConstructor;
public interface ValueConstructor<K, V> {
V create(K key);
}
public V interned(K key) {
V existingKey = storage.get(key);
V newKey = null;
if (existingKey == null) {
newKey = valueConstructor.create(key);
existingKey = storage.putIfAbsent(key, newKey);
}
return existingKey != null ? existingKey : newKey;
}
}
省略了部分非关注代码……
ValueConstructor是函数式接口,作用是传入key获得value值,JDK8引入的新特性。
重点关