- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 143字
- 2021-06-25 20:52:32
Synchronized singleton with double-checked locking mechanism
The previous implementation is thread-safe but it introduces an unnecessary delay: the block that checks whether the instance has already been created is synchronized. This means that the block can be executed by only one thread at a time, but locking makes sense only when the instance has not been created. When the singleton instance has already been created, each thread can get the current instance in an unsynchronized manner.
Adding an additional condition before the synchronized block will move the thread-safe locking only when the singleton has not been instantiated yet:
if (instance == null)
{
synchronized (SingletonSync2.class)
{
if (instance == null)
instance = new SingletonSync2();
}
}
Note that instance == null is checked twice. This is necessary, because we have to make sure a check is done in the synchronized block too.
推薦閱讀
- Modular Programming with Python
- MySQL 8從入門到精通(視頻教學版)
- Oracle Database In-Memory(架構與實踐)
- C語言開發基礎教程(Dev-C++)(第2版)
- Visualforce Developer’s guide
- Python入門很輕松(微課超值版)
- PHP 8從入門到精通(視頻教學版)
- Scrapy網絡爬蟲實戰
- Mastering Embedded Linux Programming
- 體驗之道:從需求到實踐的用戶體驗實戰
- Building Microservices with Go
- 美麗洞察力:從化妝品行業看顧客需求洞察
- 樹莓派開發從零開始學:超好玩的智能小硬件制作書
- 深入淺出Rust
- Visual FoxPro程序設計