package com.datastax.oss.driver.internal.core.util.concurrent;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import net.jcip.annotations.ThreadSafe;
@ThreadSafe
public class LazyReference<T> {
private final String name;
private final Supplier<T> supplier;
private final CycleDetector checker;
private volatile T value;
private ReentrantLock lock = new ReentrantLock();
public LazyReference(String name, Supplier<T> supplier, CycleDetector cycleDetector) {
this.name = name;
this.supplier = supplier;
this.checker = cycleDetector;
}
public LazyReference(Supplier<T> supplier) {
this(null, supplier, null);
}
public T get() {
T t = value;
if (t == null) {
if (checker != null) {
checker.onTryLock(this);
}
lock.lock();
try {
if (checker != null) {
checker.onLockAcquired(this);
}
t = value;
if (t == null) {
value = t = supplier.get();
}
} finally {
if (checker != null) {
checker.onReleaseLock(this);
}
lock.unlock();
}
}
return t;
}
public String getName() {
return name;
}
}