ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

How to create thread-safe singleton in Java using double checked locking?

user-image
تم إضافة السؤال من قبل Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
تاريخ النشر: 2013/09/01
George El Haddad
من قبل George El Haddad , Software Engineer (Freelance) , Scientific Software Consultancy & Training

Double checked locking is not recomended in programming best practices mainly due to the fact that it can be unsafe and in most places it is considered an Anti-Pattern. The case where double checked locking becomes unsafe is documented on Wikipedia

Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B (either because A has not finished initializing it or because some of the initialized values in the object have not yet percolated to the memory B uses (cache coherence)), the program will likely crash.

There are effectively3 correct ways to acheive the same result, but each one comes with different performance impacts.

  1. Synchronize the method: Correct but takes a big performance hit
  2. Use the volatile keyword for your instance: Correct and has performance gains but only to be used on Java1.5 and up (volatile implemenation on Java1.4 and below is broken)
  3. Use final wrapper: Correct and you can avoid using the volatile keyword

Performacne between using a final wrapper and volatile keyword may not be big, as always it is recommended to benchmark your options to suite your requirements.

المزيد من الأسئلة المماثلة

هل تحتاج لمساعدة في كتابة سيرة ذاتية تحتوي على الكلمات الدلالية التي يبحث عنها أصحاب العمل؟