Java渴望单例创建线程安全吗? [英] Is Java eager singleton creation thread safe?

查看:112
本文介绍了Java渴望单例创建线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢java中热切单身的简单性,大多数关于它的文章称其创建线程安全。

I like the simplicity of the eager singleton in java, and most articles about it call its creation thread safe.

class Singleton {

public static final Singleton instance = new Singleton ();

    private Singleton (){};

    public static Singleton getInstance(){

        return instance;

    }
}

但是我听到一些声称毕竟它的创建可能不是线程安全的。例如,一个消息来源声称如果使用多于1个类加载器或App域则不安全。

However I have heard some claims that its creation might not be thread safe after all. For example one source claimed that it is not safe if more than 1 class loader or App domain is used.

JVM保证Eager Singleton的创建是线程安全的,因此,例如,2个线程不会意外地同时创建单例?

Is the creation of the Eager Singleton guaranteed by the JVM to be thread safe, so that, for example, 2 threads don't accidentally create the singleton at the same time?

编辑:
对象创建的线程安全性是否需要关键字final?如果该字段不是最终的,它不是线程吗?

Is the keyword final required for thread safet of the object creation? Is it not thread if the field is not final?

推荐答案

您使用的方法是线程安全的。由于您没有引用您所说的声明,我无法直接解决它们。
但Java语言规范对此主题很清楚。

The approach that you use is thread safe. Since you haven't referenced the claims that you are talking about, I cannot directly address them. But the Java Language Specification is clear on this topic.

第17.5节它描述了


final 字段还允许程序员在没有同步的情况下实现线程安全的不可变
对象。
线程安全的不可变对象是
被所有线程看作不可变,即使数据争用用于将
引用传递给线程之间的不可变对象。这可以提供
安全保证,防止不正确或
恶意代码滥用不可变类。必须正确使用final字段才能提供
的不变性保证。

final fields also allow programmers to implement thread-safe immutable objects without synchronization. A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.


构造函数完成时,对象被认为已完全初始化。在该对象完全初始化之后只能看到对
对象的引用的线程保证
,以查看该对象的最终
字段的正确初始化值。

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

这篇关于Java渴望单例创建线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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