What should one prefer in case of Singleton Design Pattern.
1)make whole getInstance() method synchronized
OR
2)make only critical section synchronized.
what should be one’s approach and why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First of all, try to consider whether or not you need lazy instantiation. If not, there’s no synchronization involved since your
INSTANCEwill be initialized at class loading time.If you do need to lazily initialize your instance, then do not make
getInstancesynchronized, as this would cause all your threads to wait for each other for no reason once the instance is initialized.If you’ll use a synchronized block inside, you need to double-check for null (outside and inside the synchronized block) to make sure you end up with only one instance; also, you need your instance to be
volatile.The best-practice approach is to have a private nested class
SingletonHolderthat initializes the instance of your singleton at load time (but is only loaded whengetInstance()of the container class is called).However, if you don’t need lazy instantiation, the best-practice is to use an enum with one constant.
Long story short, I think you’ll find it all here: http://en.wikipedia.org/wiki/Singleton_pattern