It seems like I'm missing the important concept of class locking and the class loading event associated with it. According to my knowledge in java, we can use any class only if the classloader has already loaded the class (byte code) into memory. Based on this assumption, I thought that "the static block of the SharedQ class should be executed when the statement is synchronized (SharedQ.class) {...} is executed in the lower code." But this is not the same. Can someone explain what is happening here.
public class VerifyClassLoadingOnClassLock {
public static void main(String[] args) {
show();
}
private static void show() {
synchronized (SharedQ.class) {
System.out.println(" Method Show() executing from Main() .... ");
}
}
}
public class SharedQ {
static {
System.out.println(" Classloader is loading SharedQ ");
}
public static void writeStream() {
}
}
Output: Method Show() executing from Main() ....
source
share