I am trying to figure out the answer to the following MC question. I have tried looking for an answer on google but people seem to have different answers for this problem. Can someone please explain their answer.
public class Gingleton {
private static Gingleton INSTANCE = null;
public static Gingleton getInstance()
{
if ( INSTANCE == null )
{
INSTANCE = new Gingleton();
}
return INSTANCE;
}
private Gingleton() {
}
}
More than one instance of Gingleton can be created (My choice)
A Gingleton will never be created
The constructor is private and can't be called
value can be garbage collected, and the call to getInstance may return garbage data
New instance creation in getInstance() is not synchronized in any way, so it IS possible that more than one instance will be created in mulithreaded environment. To ensure only one instance you should do:
public class Gingleton {
// volatile
private static volatile Gingleton INSTANCE = null;
public static Gingleton getInstance()
{
if ( INSTANCE == null )
{
synchronized (Gingleton.class) { // Synchronized
if ( INSTANCE == null )
{
INSTANCE = new Gingleton();
}
}
}
return INSTANCE;
}
private Gingleton() {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With