Java 中的这种弱单例实现是线程安全的(和 GC 安全的)吗?

Is this weak singleton implementation in Java thread-safe (and GC-safe)?

我想达到以下效果:

这是我想出的代码:

public final class MyClass {
    private static WeakReference<MyClass> instance;
    public static synchronized MyClass getInstance() {
        if ((instance == null) || (instance.get() == null)) {
            instance = new WeakReference<MyClass>(new MyClass());
        }
        // TODO what if GC strikes here?
        return instance.get();
    }
}

设计选择是:

问题:

MyClass 的本地副本保存在变量中,而不是仅将引用的唯一副本提供给 WeakRefrence 的构造函数。这将防止 GC 在 new WeakReference<MyClass> 调用和函数返回之间收集 instance

public final class MyClass {
    private static WeakReference<MyClass> instance;
    public static synchronized MyClass getInstance() {
        MyClass classInstance = null;
        if (instance != null) {
            classInstance = instance.get();
            if(classInstance != null)
            {
                return classInstance;
            }
        }

        classInstance = new MyClass();
        instance = new WeakReference<MyClass>(classInstance);

        //This is now a strong reference and can't be GC'ed between the previous line and this one.
        return classInstance;
    }
}