- 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.
推薦閱讀
- Monkey Game Development:Beginner's Guide
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- Mastering Python High Performance
- C語言程序設計
- Java高并發核心編程(卷1):NIO、Netty、Redis、ZooKeeper
- 3ds Max印象 電視欄目包裝動畫與特效制作
- C編程技巧:117個問題解決方案示例
- ASP.NET Web API Security Essentials
- Angular Design Patterns
- Visual Basic程序設計實驗指導及考試指南
- Android技術內幕(系統卷)
- SQL Server 2014 Development Essentials
- Internet of Things with Arduino Cookbook
- ACE技術內幕:深入解析ACE架構設計與實現原理
- Java 開發從入門到精通