我需要一个允许同时设置一个值最多一次的结构。
具有类似于 putIfAbsent和computeIfAbsent的方法的东西ConcurrentHashMap。
interface MyContainer<T>{
void putIfAbsent(T value);
void computeIfAbsent(Supplier<T> supp);
Optional<T> maybeValue();
}
// this implementation just shows intention
class DumbContainerImpl<T> implements MyContainer<T>{
String key = "ONLYONE";
ConcurrentHashMap map = new ConcurrentHashMap<String, T>(1);
void putIfAbsent(T value){
map.putIfAbsent(key, value);
}
void computeIfAbsent(Supplier<T> supp){
map.computeIfAbsent(key, k -> supp.get());
}
Optional<T> maybeValue(){
return Optional.ofNullable(map.get(key))
}
}
标准 Java 库中有类似的东西吗?(任何 JDK 版本)