0% completed
Class Loading and Initialization
On This Page
What are the steps of class loading?
How does the parent delegation model work?
When exactly is a class initialized?
What is the difference between ClassNotFoundException and NoClassDefFoundError?
Predict the Output
Key Takeaways
A program calls the same static method of PriceService twice, and it catches the error each time. It prints these lines:
attempt 1: java.lang.ExceptionInInitializerError cause: java.lang.NumberFormatException attempt 2: java.lang.NoClassDefFoundError
The code and the data were the same in both attempts, so why are the errors different? The reason is that the JVM initializes a class at most once and remembers whether that succeeded.
This lesson follows a class from its file to its first use in four parts: the steps, the class loaders that find a class, the events that start its initialization, and the errors that report a failure.
What are the steps of class loading?
Level: Mid-level
The JVM brings a class into use in three steps: loading, linking, and initialization. Loading finds the bytes of the class, linking checks them and reserves the static fields, and initialization runs the static code of the class.
- Loading. A class loader finds the class file by name and reads it. The JVM creates a
Classobject, which represents the class inside the program. - Linking. This step has three parts. Verification checks that the bytecode is valid. Preparation creates the static fields and gives them default values, such as 0 and
null. Resolution replaces the names of other classes, fields, and methods with direct references. - Initialization. The JVM runs the initializers of the static fields and the static blocks, in the order in which they appear in the source file.
Resolution does not need to happen at once. The JVM Specification allows an implementation to resolve each name when it is first used, and HotSpot works in this way. A class that is never used may therefore be missing without any error.
The program below separates loading from initialization. The value false in the call to Class.forName() asks for a class that is not initialized.
loaded: Stock declared fields: 1 first use: static block of Stock, apples = 50 apples = 40 second use: apples = 40
After the first line the class Stock is loaded, and reflection can even count its fields, yet its static code has not run. The first read of Stock.apples starts the initialization. The field receives 50, then the static block prints that value and changes it to 40. The second read finds an initialized class, so nothing runs again.
Look at the lower row, which follows the field apples through the steps. It exists from preparation onward, with the default value 0, before any code of the class has run.
Common mistake: Using the words "loaded" and "initialized" as if they meant the same. A loaded class can wait for its initialization for the whole run of a program.
Follow-up questions
1. Why does the JVM verify bytecode that javac has already checked?
The JVM cannot know that a class file was written by javac. A file can be damaged, changed by a tool, or created by hand to break the rules of the language. Verification proves, for example, that an instruction never treats an int as a reference. The interpreter and the compilers can then work without repeating these checks.
2. Is a class loaded when a variable of its type is declared?
<details><summary>Show answer</summary>The specification leaves this open, but a declaration alone does not initialize the class. A JVM may load the class early or late. It must behave as if a loading error appeared at the first use of the class. Programs should depend on the rules of initialization, which are exact.
</details>How does the parent delegation model work?
Level: Mid-level
A class loader that receives a request first passes it to its parent loader, and it searches for the class itself only when the parent finds nothing. Requests therefore travel to the top, and the highest loader that knows the class provides it.
The JVM has three built-in loaders:
| Loader | Provides | Parent |
|---|---|---|
| Bootstrap | Core classes, such as java.lang.String | None |
| Platform | Other classes of the Java platform, such as java.sql.Timestamp | Bootstrap |
| Application | Classes from the class path of the program | Platform |
Every Class object knows its loader. The bootstrap loader is part of the JVM and is represented by null, so getClassLoader() returns null for its classes.
loader: app loader: platform loader: null (bootstrap) String: null java.sql.Timestamp: platform Solution: app
The first three lines follow getParent() from the loader of the program to the top. The other lines name the loader that provided each class.
Notice that both requests travel upward first. The request for Solution comes back, because neither parent has such a class.
This order protects the core classes. Suppose a library contains its own java.lang.String. A request for that name reaches the bootstrap loader, which returns the real class, so the copy is never used. Two further checks exist: javac rejects the source file because the package belongs to the module java.base, and a custom loader cannot define a class whose name starts with java..
Since Java 9, the built-in loaders first look up which module contains the package. They delegate to the parent for a class that is in no module, such as the classes of an ordinary class path.
Common mistake: Describing the parent loader as a superclass. The relation is between objects: each loader object has a reference to its parent, and the classes of the loaders do not need to inherit from each other.
Follow-up questions
1. Can the same class be loaded twice in one JVM?
<details><summary>Show answer</summary>Yes, two class loaders can each define a class from the same class file. The JVM identifies a class by its name together with the loader that defined it. The two results have equal names but are different classes, and a cast from one to the other throws ClassCastException.
2. Does every class loader ask its parent first?
<details><summary>Show answer</summary>No, delegation is a convention that a custom loader can change. The Tomcat web server searches the files of a web application before it asks the shared loader of the server. Two applications on one server can therefore use different versions of one library. Core classes are still requested from the bootstrap loader first.
</details>When exactly is a class initialized?
Level: Senior
A class is initialized immediately before its first active use: when an instance is created, when one of its static methods is called, or when one of its static fields is assigned or read. Reading a constant variable is an exception. Initializing a class also initializes its superclass first.
A constant variable is a final variable of a primitive type or String whose initializer is a constant expression, such as 120 or "apple". The compiler copies its value into the class that uses it, so the declaring class is not involved at run time.
The class Fruit below extends Product, and each class prints a line in its static block.
1. class literal Fruit 2. new array length 3 3. inherited static field Product initialized 4 4. static method Fruit initialized fruit 5. new object
Steps 1 and 2 initialize nothing, because neither a class literal nor the creation of an array is one of the events listed above. Step 3 reads Fruit.count, but Product declares the field, so only Product is initialized. Step 4 initializes Fruit. Step 5 prints nothing more, because both classes are ready.
Some reflective calls also cause initialization, for example Class.forName("Stock") with one argument.
Common mistake: Saying that all classes are initialized when the program starts. The launcher initializes the main class before it calls main. Apart from the supertypes that are initialized with it, the other classes of the program wait until a use initializes them.
Follow-up questions
1. What happens when two threads use a class for the first time at the same moment?
<details><summary>Show answer</summary>One thread initializes the class, and the other waits until the initialization is complete. The JVM uses a lock for each class. The static code therefore runs once, and the waiting thread sees the results. Programs rely on this rule to create a shared object safely in a static field.
</details>2. Does initializing a class also initialize its interfaces?
<details><summary>Show answer</summary>It initializes the superinterfaces that declare a default method, and not those with only abstract and static methods. A default method is an interface method with a body that a class inherits. The other interfaces are initialized when one of their own fields or static methods is used, and a field that is a constant variable does not count.
</details>What is the difference between ClassNotFoundException and NoClassDefFoundError?
Level: Senior
ClassNotFoundException is thrown when code asks for a class by name and no loader finds it, while NoClassDefFoundError is thrown when the JVM needs a class for compiled code and cannot get its definition. The first is a checked exception, and the second is an error.
ClassNotFoundException | NoClassDefFoundError | |
|---|---|---|
| Kind | Checked exception | Error |
| Typical source | Class.forName(), loadClass() | A new expression or static call |
| Usual cause | Wrong name, missing library | Missing library, or failed initialization |
A NoClassDefFoundError means that the class existed when the code was compiled. We compiled two classes, deleted Receipt.class, and ran the program. The output is shortened to its first five lines.
Checkout starts Exception in thread "main" java.lang.NoClassDefFoundError: Receipt at Checkout.main(Checkout.java:4) Caused by: java.lang.ClassNotFoundException: Receipt at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
The program ran until it needed the missing class. A loader then threw ClassNotFoundException, and the JVM reported it as the cause of the error.
A failed initialization leads to the same error in a different way. When static code throws an exception that is not an Error, the JVM wraps it in ExceptionInInitializerError. An Error is thrown without a wrapper. In both cases, the JVM marks the class as unusable. Each later use throws NoClassDefFoundError, although the class file is present. The program below shows both attempts from the start of this lesson, and then a wrong name.
attempt 1: java.lang.ExceptionInInitializerError cause: java.lang.NumberFormatException attempt 2: java.lang.NoClassDefFoundError forName: java.lang.ClassNotFoundException
Common mistake: Searching for a missing library whenever NoClassDefFoundError appears. If its message starts with "Could not initialize class", the class was found, and its static code failed earlier.
Follow-up questions
1. How do you find the original cause of "Could not initialize class"?
<details><summary>Show answer</summary>Find the first ExceptionInInitializerError in the log, because its cause is the original exception. It may appear much earlier, in a different thread. Since Java 18, and in some later updates of older versions, the NoClassDefFoundError also has a cause that repeats the original exception and the name of the thread.
2. Can a program initialize the class again after the failure?
<details><summary>Show answer</summary>No, the class stays in the failed state for as long as its loader is in use. The JVM throws the error for each new attempt and does not run the static code again. Recovery needs a restart, or a new class loader that loads the class once more. For this reason, static code should not depend on files or network calls that can fail.
</details>Predict the Output
The class Prices has four static fields and a static block that prints a line. Decide where that line appears among the others, and then press Run.
The program prints start, 120, apple, Prices initialized, 45, and 290. APPLE and FRUIT are constant variables, so the compiler has copied 120 and "apple" into the main class, and reading them initializes nothing. BANANA is final, but its type is Integer, and a constant variable must have a primitive type or be a String. Reading it therefore initializes Prices, which prints the line before 45. The static block also assigns 290 to cherry, so the last line prints 290.
Key Takeaways
- A class is loaded, then linked, and then initialized, and initialization can happen much later than loading.
- A class loader normally asks its parent first, so core classes come from the bootstrap loader.
- The first instance, static method call, or use of a static field that is not a constant initializes a class.
- A missing class gives
ClassNotFoundExceptionfor a request by name andNoClassDefFoundErrorfor compiled code. - An exception in a static initializer gives
ExceptionInInitializerErroronce andNoClassDefFoundErroron later uses.
The launcher starts all of this work when it loads one particular class, the class that contains main. The lesson The main Method and Program Startup explains what the launcher expects from that class and how the program ends.
Reading Progress
0%
On This Page
What are the steps of class loading?
How does the parent delegation model work?
When exactly is a class initialized?
What is the difference between ClassNotFoundException and NoClassDefFoundError?
Predict the Output
Key Takeaways