-1

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.

Eugene Kartoyev
  • 501
  • 4
  • 11
  • 4
    No, static initializers are called once: the time the class is invoked for the first time – user711189 Jul 08 '18 at 18:15
  • @geo strictly speaking the time at which the class is loaded - and this can happen more than once if, for example, it's loaded into multiple classloaders. – Boris the Spider Jul 08 '18 at 18:26
  • @BoristheSpider I am not sure about that detail (I think the spec does *not* say *loading* implicitly). It could also be first usage ... – GhostCat Jul 08 '18 at 18:29

1 Answers1

1

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

Sami Tahri
  • 1,077
  • 9
  • 19