Download constants at program startup

When I define static or constant members, for example:
public static final Font BIG_FONT = new Font("", Font.BOLD, 18);
I noticed that they only load on first use, which either freezes at runtime or makes me somehow preload them, forcibly "using" the constant when the program starts.

Not static members of this type should be loaded at program startup, and not wait for loading at first use? How can I make sure they are preloaded?

Thanks in advance.

+4
source share
4 answers

In Java, static is initialized the first time a class is used, and not the first time a static member is used. You can force "preload" using any other member of this class, not necessarily a static field.

+2
source

No.

Static initializers are executed the first time the class is loaded.

The Java Runtime makes no attempt to initialize each class immediately after starting the program; it will be a very bad idea.

+2
source

what you can do is create a static loader method and enable it during your initialization method.

+2
source

As mentioned earlier, static is initialized the first time the class is loaded.

One way to force this would be to either create an instance of the class in question, or create a (program) separate (new) class containing the statics and create an instance as soon as the program starts. However, I am not sure I would recommend any practice, as they bind a memory that can be better used elsewhere.

+1
source

Source: https://habr.com/ru/post/1388811/


All Articles