Amazon Interview Question
Software Engineer / Developerspublic class MySingleton {
//the static singleton object
private static MySingleton theObject;
/**
* private constructor
*/
private MySingleton() {
}
/**
* Checks if the singleton object is created or not,
* if not it creates the object and then the object is
* returned.
*
* @return the singleton object
*/
public static MySingleton createMySingleton() {
if (theObject == null)
theObject = new MySingleton();
return theObject;
}
}
// Also an error, synchronization does not prevent
// two calls of constructor.
public static MySingleton getInstance() {
if (_instance==null) {
synchronized (MySingleton.class) {
_instance = new MySingleton();
}
}
return _instance;
}
In the correct solution, seen in Soultion 3, make getInstance() a synchronized method:
Solution 2
// Double-checked locking -- don't use
public static MySingleton getInstance() {
if (_instance==null) {
synchronized (MySingleton.class) {
if (_instance==null) {
_instance = new MySingleton();
}
}
}
}
Solution 3
// correct solution
public static synchronized MySingleton getInstance() {
// . . . continue as in Listing 3
public class MySingleton {
//the static singleton object
private static final MySingleton theObject = new MySingleton();
/**
* private constructor
*/
private MySingleton() {
}
public MySingleton getInstance() { return theObject;}
}
isn't that the simplest thread-safe way?
- ano nee miss February 04, 2011