java - Java中是否有一个标准的解决方案来设置一次并发值?
问题描述
我需要一个允许同时设置一个值最多一次的结构。
具有类似于 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 版本)
解决方案
AtomicReference
可以用一个,用它的方法compareAndSet()
。
class AtomicContainer<T> implements MyContainer<T> {
private final AtomicReference<T> ref = new AtomicReference<>();
@Override
public boolean putIfAbsent(T value) {
if (value == null)
throw new NullPointerException();
return this.ref.compareAndSet(null, value);
}
@Override
public boolean computeIfAbsent(Supplier<T> supp) {
if (this.ref.get() == null)
return putIfAbsent(supp.get());
return false;
}
@Override
public Optional<T> maybeValue() {
return Optional.ofNullable(this.ref.get());
}
}
interface MyContainer<T> {
/**
* @return true if the given value was assigned, false if a value was already assigned
*/
boolean putIfAbsent(T value);
/**
* @return true if a value from the given supplier was assigned, false if a value was already assigned
*/
boolean computeIfAbsent(Supplier<T> supp);
Optional<T> maybeValue();
}
推荐阅读
- c# - 如果您在 groupBy 和 Sum 之后返回 dataTable,则使用 Linq 或任何其他方式使用 Sum 转换 Datatable GroupBy 多列
- java - 使用 Guava 库的 Java 中布隆过滤器的交集和并集
- nexus - 通过升级代理将数据从 Nexus2 迁移到 Nexus3
- logistic-regression - StatsModels api 上的交叉验证
- java - A*-Search 评估似乎比贪婪搜索执行得更差
- python - VSCode 无法识别从 conda 安装的 linter pycodestyle
- r - 在 R 数据框中,如何以简单的方式更改数值变量
- flutter - 如何在 Global Snackbar 中制作进度指示器(下载百分比)?
- python - 如何根据熊猫中的条件打破数据框行?
- typescript - 在 Typescript 中访问动态/泛型类的属性