Samsung Interview Question
Below code will check for the instance before it acquires the lock.
class CSingleton
{
private:
CSingleton *mInstance;
...
public:
Static Csingleton* getInstance()
{
if(mInstance==NULL)
{
AcquireLock();
if(mInstance==NULL)
mInstance=new CSingleton();
ReleaseLock();
return mInstance;
}
}
}
I don't know about other languages but in C#, a good idea would be to use an inner class to create an instance of the parent class.
Since locks on placed on classes our code will be thread safe. Copying code from C# 3.0 design patterns
public class Singleton{
Singleton(){}//private constructor
class SingletonCreator{
static SingleTonCreator(){}
internal static readonly
Singleton UniqueInstance= new Singleton();
}
public static Singleton UniqueInstance {
get {return SingletonCreator.uniqueInstance;}
}}
public class MyClass {
private static MyClass ms_instance;
private MyClass() {}
public static MyClass getInstance()
{
if (ms_instance == null){
synchronized(this){
if (ms_instance == null) {
ms_instance = new MyClass();
return ms_instance;
}
else
return ms_instance;
}
}
else
return ms_instance;
}
The code given in first comment is missing a private constructor. You will have to define a private constructor else a default constructor will be given that will have default access. So i can create instances using that constructor in the same package.
SO ur class is not singleton.
The code by tetura is also missing 1 thing. It is not thread safe. Although chances of race condition is very less. The problem is that the method needs to be synchronized and not the block. Because a race condition can occur on the first line if (ms_instance == null). For example, a thread checks and finds it is not null and is sent to runnable state. The other thread comes and checks and finds ms_instance to be null also. SO now both will create instances.
There is one more big error in tetura code snippet.
He is calling synchronized on the current object. There is no current object there. The method will be called in a static context i.e MyClass.getInstance. SO a proper synchronize will be on the class object . synchronized(Myclass.class)
class CSingleton
- Anonymous May 23, 2010{
private:
CSingleton *mInstance;
...
public:
Static Csingleton* getInstance()
{
AcquireLock();
if(mInstance==NULL)
mInstance=new CSingleton();
ReleaseLock();
return mInstance;
}
}
AcquireLock/ReleaseLock can be implemented using various different lock semantics.