When should classes be initialized - at boot time or at first use?

You can dynamically load a class using this java.lang.Class method:

 public static Class<?> forName(String name, boolean initialize, ClassLoader loader) 

According to JavaDoc , the second parameter is used to control the initialization time of the class (execution of static initialization code). If true , the class is initialized after loading and during the execution of this method; if false , initialization is delayed until the first use of the class.

Now I understand all this, but the documents do not say how to decide which strategy to use. Is it always better to do initialization immediately? Is it always better to delay it for the first use? Does it depend on the circumstances?

+8
java classloader
source share
1 answer

Yes, it depends on the circumstances, but it is usually recommended that you simply load the classes and initialize them the first time you use them.

Cases when you may need early initialization (for example, calling forName() for them):

  • Static initialization blocks can check external resources (for example, files, database connections), and if they do not work, you don’t even want to continue executing your program.
  • Like the previous one: loading external, native libraries. If they do not work (or are not suitable for the current platform), you may find this earlier and not continue your application.
  • Static initialization blocks can perform lengthy operations, and you do not want to have delays or delays later when they are really needed, you can initialize them earlier or on different background threads.
  • If you have static configuration files in which class names are specified as text, you can initialize / load them first to detect configuration / typo errors. Such examples are logger, web.xml, spring, etc. configuration files.
  • Many Java standard library classes cache specific data, such as HTTPUrlConnection , cache the HTTP user agent returned by System.getProperty("http.agent") . When it is first used, its value will be cached, and if you change it (using System.setProperty() ), the new value will not be used. You can force this caching if you initialize the corresponding classes early, protecting them later.

Cases where you should not initialize early:

  • Classes that may be required only in rare cases, or they may not even be needed at all throughout your application. For example, a GUI application can only display the About dialog when the user selects the Help / About menu. Obviously, you do not need to load the appropriate classes early (for example, AboutDialog ), because this is a rare case, and in most runs the user will not do this / need it.
+5
source share

All Articles