Skip to content

Instantly share code, notes, and snippets.

@framon
Created February 2, 2016 20:38
Show Gist options
  • Save framon/d212ae8b52220989c535 to your computer and use it in GitHub Desktop.
Save framon/d212ae8b52220989c535 to your computer and use it in GitHub Desktop.
public final class Lazy<T> {
private volatile T value;
public T getOrCompute(Supplier<T> supplier) {
final T result = value; // Just one volatile read
return result == null ? maybeCompute(supplier) : result;
}
private synchronized T maybeCompute(Supplier<T> supplier) {
if (value == null) {
value = requireNonNull(supplier.get());
}
return value;
}
}
public class Point {
private final int x, y;
private final Lazy<String> lazyToString;
public Point(int x, int y) {
this.x = x;
this.y = y;
lazyToString = new Lazy<>();
}
@Override
public String toString() {
return lazyToString.getOrCompute( () -> "(" + x + ", " + y + ")");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment