Java中是否有一个标准的解决方案,用于只设置一次并发值?
我需要一个允许同时最多设置一次值的结构。Java中是否有一个标准的解决方案,用于只设置一次并发值?,java,concurrency,concurrenthashmap,Java,Concurrency,Concurrenthashmap,我需要一个允许同时最多设置一次值的结构。 具有类似于ConcurrentHashMap的putIfAbsent和computeIfAbsent的方法的东西 interface MyContainer<T>{ void putIfAbsent(T value); void computeIfAbsent(Supplier<T> supp); Optional<T> maybeValue(); } // this implementati
具有类似于
ConcurrentHashMap
的putIfAbsent
和computeIfAbsent
的方法的东西
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))
}
}
接口MyContainer{
无效putIfAbsent(T值);
无效计算(供应商支持);
可选的maybeValue();
}
//这个实现只是显示了我们的意图
类DumbContainerImpl实现MyContainer{
String key=“ONLYONE”;
ConcurrentHashMap=新的ConcurrentHashMap(1);
无效putIfAbsent(T值){
map.putIfAbsent(键、值);
}
已发送无效计算(供应商支持){
map.computeIfAbsent(key,k->supp.get());
}
可选的maybeValue(){
返回可选的.ofNullable(map.get(key))
}
}
标准Java库中是否有类似的内容?(任何JDK版本)可以使用An及其方法
类AtomicContainer实现MyContainer{
私有最终原子引用ref=新原子引用();
@凌驾
公共布尔值putIfAbsent(T值){
如果(值==null)
抛出新的NullPointerException();
返回此.ref.compareAndSet(null,值);
}
@凌驾
公共布尔计算机(供应商支持){
if(this.ref.get()==null)
返回putIfAbsent(supp.get());
返回false;
}
@凌驾
公共可选的maybeValue(){
返回可选的.ofNullable(this.ref.get());
}
}
接口MyContainer{
/**
*@如果指定了给定值,则返回true;如果已指定值,则返回false
*/
布尔putIfAbsent(T值);
/**
*@如果指定了来自给定供应商的值,则返回true;如果已经指定了值,则返回false
*/
布尔计算(供应商支持);
可选的maybeValue();
}
可以使用An及其方法
类AtomicContainer实现MyContainer{
私有最终原子引用ref=新原子引用();
@凌驾
公共布尔值putIfAbsent(T值){
如果(值==null)
抛出新的NullPointerException();
返回此.ref.compareAndSet(null,值);
}
@凌驾
公共布尔计算机(供应商支持){
if(this.ref.get()==null)
返回putIfAbsent(supp.get());
返回false;
}
@凌驾
公共可选的maybeValue(){
返回可选的.ofNullable(this.ref.get());
}
}
接口MyContainer{
/**
*@如果指定了给定值,则返回true;如果已指定值,则返回false
*/
布尔putIfAbsent(T值);
/**
*@如果指定了来自给定供应商的值,则返回true;如果已经指定了值,则返回false
*/
布尔计算(供应商支持);
可选的maybeValue();
}
我不确定我是否理解这个问题,你的意思是类似AtomicReference的东西,如果不是,为什么不?@NickL我把这个问题理解为类似AtomicReference的东西,初始化为null,但一旦分配了一个非null值,它就变得不可变(“最多设置一次值”)。我不确定我是否理解这个问题,你的意思是类似AtomicReference的东西吗?如果不是,为什么不是?@NickL我把这个问题理解为类似AtomicReference的东西,初始化为null,但一旦分配了一个非null值,它就变得不可变(“最多设置一次值”)。