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

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();
}
主站蜘蛛池模板: 浮梁县| 来凤县| 海林市| 缙云县| 班玛县| 南康市| 大邑县| 察哈| 东辽县| 新邵县| 湘阴县| 石门县| 榆中县| 长子县| 万年县| 宁夏| 绍兴县| 静宁县| 彰武县| 遂昌县| 吐鲁番市| 离岛区| 姚安县| 西城区| 满城县| 图们市| 台东市| 康马县| 县级市| 桐乡市| 夏河县| 商城县| 特克斯县| 巴青县| 昌邑市| 平原县| 商水县| 盐边县| 铁力市| 什邡市| 全椒县|