- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 245字
- 2021-06-25 20:52:32
Synchronized singletons
The code for synchronized singletons is simple and efficient, but there is a situation we should take into consideration. If we use our code in a multithreading application, it may be the case that two threads invoke the getInstance method at the same time when the instance is null. When this happens, it may be the case that the first thread proceeds to instantiate the singleton using the new operator, and, before finishing it, the second thread checks whether the singleton is null. Since the first thread didn't finish instantiating it, the second thread will find that the instance is null, so it will start instantiating it too.
This scenario may seem almost impossible, but if it takes a long time to instantiate the singleton, the likelihood of it happening is high enough that it cannot be neglected.
The solution to this problem is very simple. We have to make the block that checks whether the instance is null thread-safe. This can be done in the following two ways:
- Making the getInstance method thread-safe by adding the synchronized keyword to its declaration:
public static synchronized Singleton getInstance()
- Wrapping the if (instance == null) condition in a synchronized block. When we use the synchronized block in this context, we need to specify an object that provides the lock. We use the Singleton.class object for this, as shown in the following code snippet:
synchronized (SingletonSync2.class)
{
if (instance == null)
instance = new SingletonSync2();
}
- DB2 V9權(quán)威指南
- Power Up Your PowToon Studio Project
- Python GUI Programming Cookbook
- Mastering Python High Performance
- Learning Apache Kafka(Second Edition)
- Bootstrap 4:Responsive Web Design
- 高級語言程序設(shè)計(C語言版):基于計算思維能力培養(yǎng)
- Teaching with Google Classroom
- Spring Boot+MVC實戰(zhàn)指南
- Java程序設(shè)計與項目案例教程
- OpenCV Android Programming By Example
- Web前端開發(fā)最佳實踐
- Mastering JavaScript Promises
- Python面向?qū)ο缶幊蹋ǖ?版)
- HTML5程序開發(fā)范例寶典