Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Holiday Calendar 2016 (Day 6): Be Lazy With Java 8

DZone's Guide to

Java Holiday Calendar 2016 (Day 6): Be Lazy With Java 8

If you want your code to kick in only when you need it, then lazy initialization is just right for you. See how you can get it working in Java 8.

· Java Zone ·
Free Resource

Learn how to build stream processing applications in Java-includes reference application. Brought to you in partnership with Hazelcast.

Image title

Today's tip 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. It's 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.
}


And there you have it! Your code is nice and lazy. Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Learn how to build distributed stream processing applications in Java that elastically scale to meet demand- includes reference application.  Brought to you in partnership with Hazelcast.

Topics:
java ,lazy initialization ,java 8 ,immutable

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}