What are lazy getters in Lombok?

What is Lombok?

Project Lombok is a Java library that helps reduce boilerplate code. Java is a verbose language where repetitive code like getters, setters, etcetera, can be avoided. Lombok reduces the boilerplate code with annotations that get plugged during the build process.

Lombok can easily be added to the project as one of the dependencies.

If the project is a Gradle project, then we add the following two lines to the dependencies section of the build.gradle file:

compileOnly 'org.projectlombok:lombok:1.18.22'
annotationProcessor 'org.projectlombok:lombok:1.18.22'

If the project is a Maven project, then add the following two lines to the dependencies section of the pom.xml file:

<dependencies>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.18.22</version>
		<scope>provided</scope>
	</dependency>
</dependencies>

Lazy Getters

Certain fields of classes are expensive to compute. Recomputing the values for such fields can make the system overloaded. Hence, we can compute the value for the field once, cache it, and every time the getter for that field is invoked, the value from the cache is returned. The fields that need this kind of behavior need to be private and final.

To enable lazy behavior on a field, we pass lazy=true to the @Getter annotation. The thread safety of the expensive computation will be taken care of by Lombok.

import lombok.Getter;

public class Main {

    static class Ball {

        @Getter(lazy = true)
        private final double speed = complexPhysicsEquation();

        private double complexPhysicsEquation() {
            System.out.println("Solving complex equation...");
            return 5.643;
        }
    }

    public static void main(String[] args) {
        Ball ballObject = new Ball();
        System.out.println("1st Getter invocation - Speed of the ball - " + ballObject.getSpeed());
        System.out.println("------");
        System.out.println("2nd Getter invocation - Speed of the ball - " + ballObject.getSpeed());
    }
}
Implementation of lazy getter

Explanation

  • Line 1: We import the annotation.
  • Line 5: We define a class called Ball.
  • Lines 7-8: We define an attribute called speed. The field is annotated with the Getter annotation with the parameter lazy as true. The value of the field is the value returned by the method complexPhysicsEquation().
  • Lines 10-13: We define a method called complexPhysicsEquation(). Assume that the method computes a complex physics equation.
  • Line 17: An instance of the Ball class is created called ballObject.
  • Lines 18-20: We invoke the getter method of the speed field twice. The first time the getter is invoked, the complexPhysicsEquation() method is executed and the result is cached. The second time the getter is invoked, the cached value is returned.

Free Resources