Last active
March 3, 2020 02:59
-
-
Save andrebreves/3b662d5d3577d39f08bc7a61f9f50d5e to your computer and use it in GitHub Desktop.
Thread safe lazy computation of final values using lambda.
This file contains hidden or 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
import java.util.Objects; | |
import java.util.function.Supplier; | |
public class Lazy<T> { | |
private volatile T value; | |
private final Supplier<T> supplier; | |
private volatile boolean valueComputed = false; | |
private Lazy(Supplier<T> supplier) { this.supplier = Objects.requireNonNull(supplier); } | |
public static <T> Lazy<T> computeOnce(Supplier<T> supplier) { return new Lazy<>(supplier); } | |
public T get() { | |
if (valueComputed) return value; | |
else return maybeComputeValue(); | |
} | |
private synchronized T maybeComputeValue() { | |
if (!valueComputed) { | |
value = supplier.get(); | |
valueComputed = true; | |
} | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment