官术网_书友最值得收藏!

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();
}
主站蜘蛛池模板: 武隆县| 恩平市| 封开县| 扎囊县| 祁东县| 淳安县| 合川市| 博罗县| 安西县| 六安市| 龙胜| 乌兰浩特市| 革吉县| 南汇区| 苍山县| 荣昌县| 岑巩县| 札达县| 汉中市| 仙游县| 宿迁市| 招远市| 台山市| 文成县| 民权县| 双鸭山市| 来宾市| 沈丘县| 台州市| 会理县| 崇阳县| 青岛市| 锡林郭勒盟| 西乌珠穆沁旗| 石柱| 枝江市| 娱乐| 上林县| 汪清县| 普宁市| 西乌珠穆沁旗|