How to Double-check locking in the Singleton Design pattern?
Loading
How to Double-check locking in the Singleton Design pattern?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit KumarRank #459 · 5.4K reputationPosted Sep 20, 2022, 12:33 AM EDT
Hi ,
Check this code
//thread-safety using double-check locking public sealed class Singleton {private static Singleton instance = null;private static readonly object padlock = new object();Singleton(){}public static Singleton Instance{get{if (instance == null){lock (padlock){if (instance == null){instance = new Singleton();}}}return instance;}} }Uday DodiyaRank #239 · 10.3K reputationPosted Sep 20, 2022, 12:48 AM EDT
public class DoubleCheckLocking { public static class SearchBox { private static volatile SearchBox searchBox; // private constructor private SearchBox() {} // static method to get instance public static SearchBox getInstance() { if (searchBox == null) { // first time lock synchronized (SearchBox.class) { if (searchBox == null) { // second time lock searchBox = new SearchBox(); } } } return searchBox; } }Obtaining lock on the SearchBox.class, only one thread will enter the synchronized block at a time. So the first thread enters then finds searchBox is null and creates it and then leaves the synchronized block, then the second thread enter the block then it finds that the searchBox is not null because the first thread already created it so it will not create a new instance of searchBox.
The double checked pattern is used to avoid obtaining the lock every time the code is executed. If the call are not happening together then the first condition will fail and the code execution will not execute the locking thus saving resources.