Singleton pattern interview

前端 未结 8 2166
忘了有多久
忘了有多久 2021-02-04 14:26

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

相关标签:
8条回答
  • 2021-02-04 14:47

    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.

    0 讨论(0)
  • 2021-02-04 14:48

    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:

    • Double Checked locking
    • Enum based singleton pattern

    UPDATE: Here is another great article which discusses the double checked locking

    0 讨论(0)
提交回复
热议问题