freework.function.AtomicLazyValue Maven / Gradle / Ivy
package freework.function;
import java.util.concurrent.atomic.AtomicMarkableReference;
/**
* A lazy compute value that may be updated atomically.
*
* @author vacoor
* @since 1.0
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class AtomicLazyValue implements LazyValue {
private final AtomicMarkableReference ref = new AtomicMarkableReference(null, false);
/**
* {@inheritDoc}
*/
@Override
public final V get() {
if (ref.isMarked()) {
return ref.getReference();
}
synchronized (ref) {
if (!ref.isMarked()) {
ref.compareAndSet(null, compute(), false, true);
}
}
return ref.getReference();
}
/**
* Computes lazy value.
*
* @return the lazy value
*/
protected abstract V compute();
}