Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when multiple threads ask for the same class to be loaded at same time?

In a multi-threaded environment, when multiple threads refer to a class at the same time, does the JVM end up loading the class multiple times?

If not, how does synchronization happen?

like image 584
Anoop Deshpande Avatar asked Mar 17 '19 06:03

Anoop Deshpande


1 Answers

The class will be loaded once. See jls 12.4.2

For each class or interface C, there is a unique initialization lock LC. The mapping from C to LC is left to the discretion of the Java Virtual Machine implementation. The procedure for initializing C is then as follows:

  1. Synchronize on the initialization lock, LC, for C. This involves waiting until the current thread can acquire LC.

...

like image 145
xingbin Avatar answered Oct 20 '22 19:10

xingbin