Question enthuware.ocpjp.v7.2.1001 :
Which of the following options is a valid implementation for singleton class SpeedSensor?
One of the options is this. Marked as correct:
Code: Select all
class SpeedSensor{
private static class SpeedSensorHolder {
public static SpeedSensor ss = new SpeedSensor();
}
public static SpeedSensor getSpeedSensor() {
return ss;
}
}
How this can be a valid singleton implementation, and a correct option?
1. It doesn't compile. Compilation error „ss cannot be resolved to a variable“
2. Class constructor is package private.
Other option
Code: Select all
public class SpeedSensor {
private SpeedSensor theInstance = null;
private SpeedSensor() {
}
public SpeedSensor getInstance() {
if (theInstance != null) {
theInstance = new SpeedSensor();
}
return theInstance;
}
}
Explanation says: This is one of the oldest commonly used but incorrect technique to implement a lazily loaded singleton class. However, it does not ensure that only a single instance is created when used in a multi threaded environment.
How this can be commonly used, if this option has problems:
1. There is no way to get a SpeedSensor. getInstance() is not static
2. getInstance() check if (theInstance != null). So it never initializes theInstance field, and always returns null.