- 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();
}
- Node.js Design Patterns
- Visual C++串口通信開發(fā)入門與編程實(shí)踐
- 騰訊iOS測(cè)試實(shí)踐
- Mastering Ember.js
- 算法精粹:經(jīng)典計(jì)算機(jī)科學(xué)問(wèn)題的Java實(shí)現(xiàn)
- Visual C++串口通信技術(shù)詳解(第2版)
- Learning ELK Stack
- Learning Concurrency in Kotlin
- Extreme C
- Beginning C++ Game Programming
- Learning Splunk Web Framework
- 零基礎(chǔ)學(xué)C++(升級(jí)版)
- Node.js 6.x Blueprints
- Pandas 1.x Cookbook
- Instant AppFog