本文介绍了为什么静态内部类单例线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,为什么静态嵌套类单例线程是安全的?

As the title said, why is static nested class singleton thread safe ?

public class Singleton
{
    private static class SingletonHolder
    {
        public static Singleton instance = null;
        public static Singleton getInstance(){
            if (null == instance) {
                instance = new Singleton();
            }
        }
    }

    public static Singleton getInstance()
    {
        return SingletonHolder.getInstance();
    }
}


推荐答案

您显示的代码在技术上不是线程安全的。这种狡猾的代码经常会破坏。

The code you show is not technically thread-safe. This sort of dodgy code often gets mangles.

代码如下所示:

public class Singleton  {
    private static class SingletonHolder {
        public static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}

这里我们分配一个静态初始化程序( SingletonHolder ),访问它的任何线程都会看到正确的发生在之前的关系。嵌套类没有什么特别之处,它只允许在不立即构造单例对象的情况下使用外部类。几乎可以肯定,这完全没有意义,但它似乎取悦了一些人。

Here we are assigning within a static initialiser (of SingletonHolder), which will be seen by any thread accessing it with correct happens-before relationship. There's nothing really special about the nested class, it just allows the outer class to be used without immediately constructing the singleton object. Almost certainly this is entirely pointless, but it seems to please some people.

因为[可变的]单身人士是一个非常糟糕的主意。

As ever [mutable] singletons are a really bad idea.

这篇关于为什么静态内部类单例线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:26