I am recently asked about java related question in an interview with following code, since I am very new to java and barely code in Java so I really have no idea what the follow
simple answer is 2) A Bolton will never be created
because when you create instance the constructor will call inside constructor initialization when call getInstance method then answer will be single instance will be created.
More than one instance of Bolton can be created
This option is correct due to lack of synchronization in the above code.
Suppose two threads concurrently check for null
and both will find that the value is null
and both will call the constructor (which refutes singleton).
Also there is other catch in this, even if two threads dont check for null
together but suppose one thread calls the constructor; but the constructor wont return till the object is constructed (assuming that the object is costly to create and requires time), so till the constructor returns some other thread might check for the null
condition and still find the object as null
as the object is not yet constructed.
This scenario in which some pre condition is called check-then-act which is culprit for Race.
For singleton there are two standards that are being used:
UPDATE: Here is another great article which discusses the double checked locking