Flipkart Interview Question
Software Engineer / DevelopersIn java it would be
static private ObjectType object;
public ObjectType getInstance(){
if(object!=null)return object;
object = new ObjectType()
return object;
}
@aathif, your answer is not thread safe. The thread safe way to do it is
class ObjectType {
class ObjectTypeHolder {
public static ObjectType instance = new ObjectType();
}
public static ObjectType getInstance() {
return ObjectTypeHolder.instance;
}
}
This ensures the object is only created the first time it is requested, and no more than one instance of it is ever created (due to the locking of the ClassLoader while it's loading the Holder)
public class Singleton {
// volatile is needed so that multiple thread can reconcile the instance
// semantics for volatile changed in Java 5.
private volatile static Singleton singleton;
private Singleton()
{
}
// synchronized keyword has been removed from here
public static Singleton getSingleton(){
// needed because once there is singleton available no need to acquire
// monitor again & again as it is costly
if(singleton==null) {
synchronized(Singleton.class){
// this is needed if two threads are waiting at the monitor at the
// time when singleton was getting instantiated
if(singleton==null)
singleton= new Singleton();
}
}
return singleton;
}
}
PLEASE SUGGEST A ANSWER...
- SUBHASHINI August 27, 2010