Day 6, Java Holiday Calendar 2016, Lazy

by Per Minborg

on December 6, 2016

6. Be Lazy With Java 8




Today's tips is about lazy initialization. Sometimes, we want our classes to do only what is absolutely necessary and nothing more. Immutable classes are particularly good candidates for laziness. Speedment, a Stream ORM Java Toolkit and Runtime, is using Lazy internally and you can find the complete Lazy source code here. Its free so steal it!

By copying this small Lazy class:

public final class Lazy<T> {

private volatile T value;

public T getOrCompute(Supplier<T> supplier) {
final T result = value; // Read volatile just once...
return result == null ? maybeCompute(supplier) : result;
}

private synchronized T maybeCompute(Supplier<T> supplier) {
if (value == null) {
value = requireNonNull(supplier.get());
}
return value;
}

}

You Can Do This:

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 + ")");
}
    // The calculation of the toString value is only done once
    // regardless if toString() is called one or several times.
    //
    // If toString() is never called, then the toString value is never
    // calculated.

}

Read more in the original article at http://minborgsjavapot.blogspot.com/2016/01/be-lazy-with-java-8.html

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

About

Per Minborg

Per Minborg is a Palo Alto based developer and architect, currently serving as CTO at Speedment, Inc. He is a regular speaker at various conferences e.g. JavaOne, DevNexus, Jdays, JUGs and Meetups. Per has 15+ US patent applications and invention disclosures. He is a JavaOne alumni and co-author of the publication “Modern Java”.