首页 > 解决方案 > Java中是否有一个标准的解决方案来设置一次并发值?

问题描述

我需要一个允许同时设置一个值最多一次的结构。
具有类似于 putIfAbsentcomputeIfAbsent的方法的东西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 版本)

标签: javaconcurrencyconcurrenthashmap

解决方案


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

}

推荐阅读