Package org.spokbjorn.lazy
Lazy loading helps with not allocating unnecessary memory to the heap when it's not needed.
Example
Lets say you have a string which is 100 MB of memory and it's not needed until the user allows the program
to continue to the System.out.println.
public class NonLazy {
// Create 100 MB worth of string
public static final String nonLazy = "A".repeat(100_000_000);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Press any key (q to quit)");
while (true) {
String input = scanner.next();
if (Objects.equals(input, "q")) {
break;
}
System.out.println(nonLazy);
}
}
}
When the program starts it will allocate 100 MB to the heap, which might not be needed as the user may have
quit the program before the System.out.println is executed.
To resolve this we can create a supplier which provides the value.
public class Supplied {
// Supply 100 MB worth of string
public static final Supplier<String> supplier = () -> "A".repeat(100_000_000);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Press any key (q to quit)");
while (true) {
String input = scanner.next();
if (Objects.equals(input, "q")) {
break;
}
System.out.println(supplier.get());
}
}
}
When the program starts it will not allocate 100 MB to the heap, but will wait until we reach the
System.out.println statement however when we reach the statement again we will allocate another
100 MB to the heap in other word grabage to the garbage collector.
To fix the problem with allocating garbage to the heap we can cache the value in a separate variable when
the supplier is called. You might have done this pattern before if you have made the singleton pattern. That
we wait to create an instance of the singleton til the consumer requires the instance. And this is
what Lazy does for you.
public class Lazily {
// Lazily create 100 MB worth of string
public static final Lazy<String> lazy = Lazy.lazy(() -> "A".repeat(100_000_000));
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Press any key (q to quit)");
while (true) {
String input = scanner.next();
if (Objects.equals(input, "q")) {
break;
}
System.out.println(lazy);
}
}
}
When the program starts it will not allocate 100 MB to the heap, but will wait until we reach the
System.out.println statement and will remain at 100 MB til the grabage colletor can release the
memory. And it may not be able to be released it if the field is static but if it is a normal it field it may.
-
ClassesClassDescriptionLazy<T>A generic class for creating a lazy-initialized value that can be computed on-demand.