Created
February 2, 2016 20:38
-
-
Save framon/d212ae8b52220989c535 to your computer and use it in GitHub Desktop.
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
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; | |
} | |
} |
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
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