class 锁定与 java classloader 相关吗?

is class locking related to java classloader?

看起来我缺少关于锁定 class 的重要概念,并且根据我在 java 中的知识,它与 class 加载 event.As 相关,我们可以使用任何 class 仅当 classloader 已经将 class(字节码)加载到内存中时。基于这个假设,我在想“静态块 SharedQ class 应该在语句同步 (SharedQ.class) { ... } 在下面的代码中执行时执行。但那是不一样的。 谁能准确解释这里发生的事情。

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() {
        // some multiThread code here
    }
}

输出是:Method Show() executing from Main() ....

class 已经加载,但不一定初始化。基本上,当您在其上同步时,有一个可用的 Class 对象,但在某些东西使用 class 的成员之前,它不必被初始化。

来自JVM specification section 5.5

Initialization of a class or interface consists of executing its class or interface initialization method (§2.9).

A class or interface may be initialized only as a result of:

  • The execution of any one of the Java Virtual Machine instructions new, getstatic, putstatic, or invokestatic that references the class or interface (§new, §getstatic, §putstatic, §invokestatic). All of these instructions reference a class directly or indirectly through either a field reference or a method reference.
  • Upon execution of a new instruction, the referenced class or interface is initialized if it has not been initialized already.
  • Upon execution of a getstatic, putstatic, or invokestatic instruction, the class or interface that declared the resolved field or method is initialized if it has not been initialized already.
  • The first invocation of a java.lang.invoke.MethodHandle instance which was the result of resolution of a method handle by the Java Virtual Machine (§5.4.3.5) and which has a kind of 2 (REF_getStatic), 4 (REF_putStatic), or 6 (REF_invokeStatic).
  • Invocation of certain reflective methods in the class library (§2.12), for example, in class Class or in package java.lang.reflect.
  • The initialization of one of its subclasses.
  • Its designation as the initial class at Java Virtual Machine start-up (§5.2).

Prior to initialization, a class or interface must be linked, that is, verified, prepared, and optionally resolved.

Section 5 of the specification 对所有这些进行了很多讨论 - 特别是,它区分了加载、链接和验证。