Search code examples
javamultithreadingconcurrencyclassloader

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?


Solution

  • 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.

    ...