Created
June 1, 2021 21:05
-
-
Save mattventura/d0dcac58b9a8645841ce88b1c137befb to your computer and use it in GitHub Desktop.
Lazy Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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