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

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();
}
主站蜘蛛池模板: 天津市| 金平| 武陟县| 个旧市| 寻乌县| 长寿区| 巴塘县| 山东| 凤阳县| 临洮县| 斗六市| 沙湾县| 浦东新区| 崇阳县| 河南省| 旌德县| 衡阳市| 小金县| 思茅市| 江北区| 胶州市| 沾化县| 灵丘县| 万荣县| 育儿| 新竹市| 岳普湖县| 武清区| 东至县| 广平县| 达日县| 拜城县| 天水市| 旺苍县| 平塘县| 安丘市| 天津市| 清涧县| 含山县| 武城县| 榆中县|