这个 Singleton 是线程安全的吗?我怎么看不出来?

Is this Singleton a thread safe one ? I can't see how?

考虑单例:

public final class MySingleton {
    private static class Nested 
    {
        private static final MySingleton INSTANCE = new MySingleton();
    }

    private MySingleton() 
    {
        if (Nested.INSTANCE != null) 
        {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static MySingleton getInstance() 
    {
        return Nested.INSTANCE;
    }
}

我没有加任何锁,但为什么这是单例问题的线程安全解决方案?

I didn't put any locks, but why is this a thread safe solution for the Singleton problem ?

因为 class 变量在它们声明的 classes 被初始化时被初始化,而 classes 在锁后面被初始化。 Java 语言规范的 Detailed Initialization Procedure 章节描述了该过程。

当您的客户端代码调用 getInstance 时,相应的线程将尝试访问 Nested.INSTANCE。如果Nested还没有初始化,当前线程会为class获取一个初始化锁并初始化。部分初始化过程会初始化finalclass字段INSTANCE.

请注意,在您给出的示例中,让 Nested class 成为 INSTANCE 的持有人毫无意义,您还不如将字段放在MySingleton class.