Given the following definition of class Main, which option,
when replacing //INSERT CODE HERE//,
implements the Singleton pattern correctly with no concurrent creation of objects of class Main?
Choose all that apply.
class Resource {} class Main { private static Main king = null; private Main() {} //INSERT CODE HERE// }
a public static synchronized Main getInstance() { if (king == null) king = new Main(); return king; }//from www.j a va 2 s .c o m b public static Main getInstance() { if (king == null) { synchronized (Resource.class){ king = new Main(); } } return king; } c public static Main getInstance() { synchronized (Resource.class){ if (king == null) { king = new Main(); } } return king; } d synchronized static public Main getInstance() { synchronized (Resource.class){ if (king == null) { king = new Main(); } } return king; }
a, c, d
In option (a), the complete method getInstance()
is synchronized, which ensures that only one Thread executes this method and creates an instance of class Main (assigning it to the static variable king), if it's null.
Option (b) is incorrect.
Method getInstance()
synchronizes only the code king = new Main()
;.
So multiple methods can still execute method getInstance()
concurrently and query whether the variable king is null.
If, say, two threads find it null, they both will execute the following code (though not at the same time):.
king = new Main();
When the second Thread executes the preceding code, it creates and assigns another object of class Main to variable king.
This method fails to prevent multiple creations of objects of class Main.
Option (c) is correct.
Method getInstance()
synchronizes the part of the method that creates an object of class Main.
When the control is within the synchronized block, the code checks again to confirm that variable king is still null.
If true, it creates an object of class Main and assigns it to the variable king.
Option (d) is correct.
It defines the same code as option (c), but with a difference: this option applies the synchronized keyword to the method also.
Though synchronizing the code block and the complete method isn't required, it isn't incorrect to do so.
Because this method prevents creation of multiple objects of class Main, it qualifies as a correct implementation of method getInstance()
.