improvments on lazy instance (#685)

This commit is contained in:
erabii
2020-12-10 20:37:58 -05:00
committed by GitHub
parent 1ff67bac5e
commit 1e203af4d9

View File

@@ -26,27 +26,29 @@ import java.util.function.Supplier;
*/
public final class LazilyInstantiate<T> implements Supplier<T> {
private volatile T t;
private final Supplier<T> supplier;
private Supplier<T> current;
private LazilyInstantiate(Supplier<T> supplier) {
this.supplier = supplier;
this.current = () -> swapper();
}
public static <T> LazilyInstantiate<T> using(Supplier<T> supplier) {
return new LazilyInstantiate<T>(supplier);
return new LazilyInstantiate<>(supplier);
}
public synchronized T get() {
return this.current.get();
}
private T swapper() {
T obj = this.supplier.get();
this.current = () -> obj;
return obj;
public T get() {
T localT = t;
if (localT == null) {
synchronized (this) {
localT = t;
if (localT == null) {
localT = supplier.get();
t = localT;
}
}
}
return localT;
}
}