Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

multithreading - Is Java eager singleton creation thread safe?

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 safe if the field is not final?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...