Ebay Interview Question
Member Technical StaffsCountry: India
Interview Type: In-Person
class Singleton
{
private:
Singleton();
Singleton(const Singleton ©);
const Singleton& operator=(const Singleton &rhs);
public:
const Singleton& GetInstance()
{
static Singleton _instance;
return _instance;
}
};
//Lazy instantiation using double locking mechanism.
class Singleton
{
private static Singleton instance;
private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class)
{
if (instance == null)
{
System.out.println("getInstance(): First time getInstance was invoked!");
instance = new Singleton();
}
}
}
return instance;
}
public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}
This can be done through the readResolve method. When an object is read, replace it with the singleton instance. This ensures that nobody can create another instance by serializing and deserializing the singleton. For Example:
public final class MySingleton {
private MySingleton() { }
private static final MySingleton INSTANCE = new MySingleton();
public static MySingleton getInstance() { return INSTANCE; }
private Object readResolve() throws ObjectStreamException {
// instead of the object we're on,
// return the class variable INSTANCE
return INSTANCE;
}
}
This will ensure that only one instance is read when we are dealing with serialization/de-serialization.
Serialize/Deserialize the Object to a Database.
- Abhi January 28, 2013Each JVM downloads the object from DB->locks the DB Row till the instance is used->Writes back the object to DB->Unlocks the row from Database.