Is Java eager singleton creation thread safe?

假装没事ソ 提交于 2019-12-19 09:26:35

问题


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;

    }
}

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.

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?

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


回答1:


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.

In section 17.5 it describes

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.




回答2:


It is thread-safe even if we remove final from public static final Singleton instance = new Singleton ();.

That's because the JVM guarantees that the instance will be created before any thread access the static instance variable.



来源:https://stackoverflow.com/questions/52687983/is-java-eager-singleton-creation-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!