In this post under Lombok, I will explain with example the purpose of “@Getter(lazy=true)” annotation.
In many cases, the values of Pojo class instance variables are fixed.
In some cases, these values have to be computed at runtime.
We can add a getter method which when called first time, will compute the value once and store it in cache before returning the value to the caller.
And then any further calls to the getter method returns the value from cache.
We can create the above getter method by creating a private final instance variable and annotating it with “@Getter(lazy=true)” annotation.
Also the field should be initialized with the method that is used to calculate the value.
For our example I am using the below Pojo class
Person class
1 package package22;
2
3 import lombok.Getter;
4
5 public class Person {
6 @Getter(lazy = true)
7 private final double[] computedValue = expensive();
8
9 private double[] expensive() {
10 System.out.println("Computing");
11 double[] result = new double[1000000];
12 for (int i = 0; i < result.length; i++) {
13 result[i] = Math.asin(i);
14 }
15 return result;
16 }
17 }
In our above Pojo class, at line 7, we have declared a private final variable named “computedValue” and initialize it to method named “expensive”.
The method “expensive” is declared in the Pojo class itself refer to line 9 to 16.
This method will compute the value when it is called. It also prints “Computing” to the console.
We have also annotated the field “computedValue” with “@Getter(lazy=true)” annotation.
Next I will show the way it is used in the main class.
Main class
1 package package22;
2
3 public class Example22 {
4 public static void main(String[] args) throws InterruptedException {
5 Person person = new Person();
6
7 System.out.println(person.getComputedValue()[11]);
8 Thread.sleep(1000);
9 System.out.println(person.getComputedValue()[11]);
10 }
11 }
In the above main class, at line 5, “Person” class instance is created.
At line 7, we are calling the “computedValue” instance variable’s getter method “getComputedValue” and print it to console.
At line 8, we wait for 1 second.
At line 9, we are again calling “getComputedValue” and printing its value to console.
Since at line 7, we are calling “getComputedValue” method first time, the instance method “expensive” is called and the value is computed and stored in the variable and in cache.
At line 9, we are calling the getter method second time and this time “expensive” method is not called and the cached value is returned.
In this way we can use “@Getter(lazy=true)” annotation.
Below is the output
Output
Computing
121.0
121.0