繁体   English   中英

Java 中是否有一个标准的解决方案,用于设置恰好一次的并发值?

[英]Is there a standard solution in Java for concurrent value set exactly once?

我需要一个允许同时设置一个值最多一次的结构。
具有类似于ConcurrentHashMapputIfAbsentcomputeIfAbsent方法的东西。

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();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM