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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,lazy initialization ,java 8 ,immutable

Published at DZone with permission of Per-Åke Minborg, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}