Skip to content

Instantly share code, notes, and snippets.

@andrebreves
Last active March 3, 2020 02:59
Show Gist options
  • Save andrebreves/3b662d5d3577d39f08bc7a61f9f50d5e to your computer and use it in GitHub Desktop.
Save andrebreves/3b662d5d3577d39f08bc7a61f9f50d5e to your computer and use it in GitHub Desktop.
Thread safe lazy computation of final values using lambda.
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