Lazy initializing your code

Many time we have static fields in our Java classes. These fields are get initialized with loading of your classes and all other static fields. But many time its not the urgent to initialize few of the fields while loading the class itself. Here the concept of lazy initialization comes in picture.

Consider the code below

public class LazyInitilaizationTest {
    public static String[] field = getStringContent();
    static {
        System.out.println("Loading Class");
    }
    
    public static String[] getStringContent(){
        System.out.println("Initializing field");
        return new String[]{};
    }
    
    public static void main(String[] args) {
        System.out.println("Accessing Field");
        System.out.println(field);
    }
}


Here the class has private & static field which gets initialized by invoking getStringContent() method. Running above class prints following output


Initializing field
Loading Class
Accessing Field


Above output says that field get initialized with loading the class, regardless when and where it is being used in the program. (“Initializing field” get displayed before “Accessing field”).


If you want to defer the initialization code whenever it will be used , you need wrap the static fields in internal private class for lazy initialization.



public class LazyInitilaizationTest {
    static {
        System.out.println("Loading Class");
    }
    
    private static class Fields {
        public static String[] field = getStringContent();
        public static String[] getStringContent(){
            System.out.println("Initializing field");
            return new String[]{};
        }
    }
    
    public static void main(String[] args) {
        System.out.println("Accessing Field");
        System.out.println(Fields.field);
     }
}

In above class an another wrapper static class is being used. The output of above code is


Loading Class
Accessing Field
Initializing field


Here you can notice initialization happened after the field has been invoked (“Accessing field” get displayed before “Initializing field”).

Comments

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester