单人模式结合懒惰加载和线程安全 [英] Singleton pattern with combination of lazy loading and thread safety

查看:112
本文介绍了单人模式结合懒惰加载和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对单身人士进行一些研究,特别是关于懒惰与单身人士的急切初始化。

I was doing some research about singletons, specifically regarding lazy vs eager initialization of singletons.

渴望初始化的一个例子:

An example of eager initialization:

public class Singleton
{
    //initialzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

但如上图所示,它是急切的初始化和线程安全性留给了jvm
,但是现在我想要这样一个模式,但是用懒惰的初始化。

but as shown above that it is eager initialization and thread safety is left to jvm but now, I want to have this same pattern but with lazy initialization.

所以我想出了这个方法: >

so I come up with this approach:

public final class Foo {
    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }
    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }
    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }
}

如上所示由于行

private static final Foo INSTANCE = new Foo(); 

仅在实际使用类FooLoader时执行,这会处理懒惰实例化,而且它保证线程安全。

is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

是否正确?

推荐答案

在我看来,您的第二个代码片段是线程安全的最佳方式,以简单的方式初始化单例。它实际上有一个模式名称

Your second code snippet is, in my opinion, the best way of thread-safe lazily initializing a singleton. It actually has a pattern name

按需初始化持有人成语

我建议你使用它。

这篇关于单人模式结合懒惰加载和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆