Reputation: 16541
This is the example:
http://www.tutorialspoint.com/java/java_using_singleton.htm
When looking at the 1st example, when user writes : Singleton.getInstance()
, then it calls out :
new Singleton()
I don't get it, how it is singleton, when everytime it creates a new singleton object?
I understand the 2nd example. If singleton
is null, then create new object, but in first example, it always creates new object??
Whats up with that?
Upvotes: 1
Views: 1556
Reputation: 11805
In the second example, as someone mentioned, it's not thread safe. Here's two options for making the getInstance() method thread safe:
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public static Singleton getInstance() {
if (singleton == null) {
synchronized(Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
The second version of the method allows you to get an already constructed singleton instance without any synchronization overhead. However, when it is null, you then enter a synchronized block. You check the null again just in case there was a thread context switch and a second thread actually gets into the synchronized block before you do. That ensures only a single instances is ever constructed.
Either approach should be entirely thread safe.
Upvotes: 1
Reputation: 8467
The line:
private static Singleton singleton = new Singleton( );
only executes once when the class is loaded -- it's a class field initializer.
Look at this question: Best Practice: Initialize class fields in constructor or at declaration? -- it's the same idea with the new Random()
in that question.
Edit: I popped in to Stack Overflow for a moment to see if I could answer an unanswered question, and before I could submit my response, it looks like three others already have answered it. I like Stack Overflow!
Upvotes: 0
Reputation: 3121
The member singleton
is declared as static, so new Singleton()
is only ever called once.
Upvotes: 0
Reputation: 143886
The new Singleton()
is only getting called when the class is loaded.
Upvotes: 0
Reputation: 1500525
No, in the first example the only call to new Singleton()
is here (within Singleton
):
private static Singleton singleton = new Singleton( );
That's a static variable initializer. It gets executed once, and only when needed. (If you never touch the Singleton
class, the initializer won't get executed.)
Upvotes: 10