Complete the code to declare the private static instance variable in the Singleton class.
private static [1] instance;The Singleton instance must be of the Singleton class type and declared static to ensure only one instance exists.
Complete the code to make the constructor private in the Singleton class.
[1] Singleton() { }The constructor must be private to prevent external instantiation of the Singleton class.
Fix the error in the getInstance method to correctly return the Singleton instance.
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return [1];
}The method should return the static instance variable, not 'this' or a new object.
Fill both blanks to implement thread-safe lazy initialization using synchronized block.
public static Singleton getInstance() {
if (instance == null) {
synchronized([1]) {
if (instance == null) {
instance = new [2]();
}
}
}
return instance;
}Use the class object for synchronization and create a new Singleton instance inside the synchronized block.
Fill all three blanks to implement the Singleton pattern with eager initialization.
public class Singleton { private static final [1] instance = new [2](); [3] Singleton() { } public static [1] getInstance() { return instance; } }
The instance is created eagerly as a static final variable. The constructor is private to prevent external instantiation.