Search code examples
javamultithreadinginitializationclassloader

Is Java class initialized by the thread which use it for the first time?


Lets assume following classes definition:

public class A {
    public final static String SOME_VALUE;

    static {
        SOME_VALUE = "some.value";
    }
}

public class B {
    private final String value = A.SOME_VALUE;
}

Assuming that the class A hasn't been loaded yet, what does happen when object of the class B is instantiated by some thread T? The class A has to be loaded and instantiated first. But my question is: if it's done in context of the thread T, or rather in context of some other (special) "classloader" thread?


Solution

  • There is no special thread for loading classes. It will be from the thread which refers to the class for the first time. The ClassLoader.loadClass method is synchronized so that multiple threads trying to load the same class don't interfere.

    EDIT Code to enumerate

    public class Arbit {
        public static void main(String[] args) throws Exception{
            B b1 = new B("1");
            B b2 = new B("2");
            B b3 = new B("3");
            b1.start();
            b2.start();
            b3.start();
            b1.join();
            b2.join();
            b3.join();
        }
    }
    
    class B extends Thread{
        B(String s){
            setName(s);
        }
        @Override
        public void run() {
    
            try {
                Thread.sleep(new Random().nextInt(100));
            } catch (InterruptedException e) {
            }
            System.out.println(A.s);
        }
    }
    
    class A{
        static String s = Thread.currentThread().getName();
    }