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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Amit KumarPosted Sep 20, 2022, 4:33 AM
Hi ,
Check this code
Uday DodiyaPosted Sep 20, 2022, 4:48 AM
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.