Search code examples
javaobjectstaticfinalpublic

Are the init methods of a static final object called again and again when I use that object?


I have a library, in which I need only one configuration all through the app. I call a method in that library through a public static final reference in a Helper class to the library' s builder.

Schematically, it looks like this:

public class Helper{
       private static final Pattern a = ... ;
       private static final Pattern b = ... ;
       ....
       public static final Library.Renderer RENDERER = Library.getBuilder().
                        .add(a)      // setting the configuration 
                        .add(b)      // of the renderer
                        ...
                        .build();
}

And, I call the method in that library from other places like this

 String processedText = Helper.RENDERER.render(rawText);

Does it mean that each time I call the static RENDERER, it passes all the process of adding and building the method again and again?

Note: this is not about static variables. It is about the methods incorporated in the static object initialization. So, the question is whether the static final RENDERER = .... refers to the adding and building procedure, or to the final outcome of that adding and building procedure.


Solution

  • No, this is called only once. Testing file :

    public static void main(String[] args) {
        int verify = Static.var;
        int verify2 = Static.var;
        System.out.println("verify:"+verify);
        System.out.println("Verify2:"+verify2);
    }
    

    And the Static class :

    public class Static {
    
        public static int var = returnCount();
    
        public static int count = 0;
        public static int returnCount() {
            count = count + 1;
            return count;
       }
    }
    

    Result :

    verify:1 Verify2:1