Skip to content

Instantly share code, notes, and snippets.

@mattventura
Created June 1, 2021 21:05
Show Gist options
  • Save mattventura/d0dcac58b9a8645841ce88b1c137befb to your computer and use it in GitHub Desktop.
Save mattventura/d0dcac58b9a8645841ce88b1c137befb to your computer and use it in GitHub Desktop.
Lazy Value
public class LazyValue<T> implements Supplier<T> {
private volatile T value;
private final Supplier<T> producer;
private final Object lock = new Object();
public LazyValue(Supplier<T> producer) {
this.producer = producer;
}
@Override
public T get() {
T localValue = value;
if (localValue == null) {
synchronized (lock) {
localValue = value;
if (localValue == null) {
value = localValue = producer.get();
}
}
}
return localValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment