In the given link ,take a look at the options given and select the option that describes the worst thing with this code:
-
So what exactly is the question here? – Hari Menon Mar 14 '13 at 12:07
-
is this an interview question..?? this question doesn't belong here – Mar 14 '13 at 12:16
-
Take a look at http://stackoverflow.com/questions/15425282/singleton-pattern-interview (that question had a better survival rate than yours) – Javier Mar 15 '13 at 06:01
3 Answers
More than one instance of Mango can be created
Yes: if two threads execute getInstance
concurrently, they could both see INSTANCE
null and create a new instance
A Mango will never be created
huh... if you call getInstance
, an instance will be created, so no.
The constructor is private and can't be called
No, it can be called from within the class by getInstance
value can be garbage collected, and the call to getInstance may return garbage data
INSTANCE
will not be garbage collected as long as it is reachable - in the case of a static variable, that is for the whole life of the JVM (*).
(*) more precisely, it will not be garbage collected as long as the class is loaded. A class could be unloaded if the associated classloader itself is garbage collected.

- 321,522
- 82
- 660
- 783
-
1
-
Thanks for the quick answer, I was confused between Garbage collection and multiple instances. – d34th4ck3r Mar 14 '13 at 12:18
this is the classic singleton object design pattern
whats worst about is dependent on the requirement. as per my understanding if this is a class of the larger program, then mango should never be made more than once.
as assylias said, until there is a synchronized keyword the result may lead to 2 objects of mango(but thats a corner case)
synchronized public static Mango getInstance()
{
if ( INSTANCE == null )
{
INSTANCE = new Mango();
}
return INSTANCE;
}

- 1,923
- 7
- 33
- 66
I think the answer is option A : "More than one instance of Mango can be created" Without proper sychronization,two or more threads may call getInstance() concurrently and that make Mango an unqualified Singleton
By the way, this looks like a homework or interview question!:)

- 1,582
- 11
- 12