malai.kuangren
malai.kuangren

Reputation: 359

Initialization of Classes and Interfaces

After I read JLS section 12.4.2.

2.If the Class object for C indicates that initialization is in progress for C by some other thread, then release LC and block the current thread until informed that the in-progress initialization has completed, at which time repeat this step.

Does the current thread really need to release LC which acquired by some other thread ? Is this action safe? How many times initialization of class or interface will happen in a App?Thanks.

Upvotes: 2

Views: 91

Answers (1)

Bohemian
Bohemian

Reputation: 425033

The contract for the JVM is that the class has finished loading before any application thread is allowed to use the class. "Finished loading" means that all static initializers have completed (ie all static blocks have executed and static fields are initialized in the order in which they are coded)

Classes are loaded when first used, so whatever thread that occurs in (implicitly) invokes the ClassLoader to load the class, and it blocks while the ClassLoader completes loading the class (as per above). Any other threads that happen to use the class while the class is being loaded, will also block waiting for the class to finish loading.

Classes are loaded once per JVM start up.


Note to pedants: Yes it is possible using ClassLoader kung fu to reload a class, but this explanation is not misleading.

Upvotes: 4

Related Questions