An AtomicReference
can be used, with its compareAndSet()
method.
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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…