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

Synchronized singleton with double-checked locking mechanism

The previous implementation is thread-safe but it introduces an unnecessary delay: the block that checks whether the instance has already been created is synchronized. This means that the block can be executed by only one thread at a time, but locking makes sense only when the instance has not been created. When the singleton instance has already been created, each thread can get the current instance in an unsynchronized manner.

Adding an additional condition before the synchronized block will move the thread-safe locking only when the singleton has not been instantiated yet:

if (instance == null)
{
synchronized (SingletonSync2.class)
{
if (instance == null)
instance = new SingletonSync2();
}
}

Note that instance == null is checked twice. This is necessary, because we have to make sure a check is done in the synchronized block too.

主站蜘蛛池模板: 鄂托克旗| 承德市| 三台县| 闵行区| 淄博市| 绍兴市| 土默特左旗| 武平县| 泰来县| 孟连| 澎湖县| 洛浦县| 湘潭市| 潮州市| 衢州市| 图片| 韩城市| 聊城市| 吴江市| 关岭| 江都市| 巴林右旗| 仁怀市| 房山区| 社旗县| 隆德县| 哈巴河县| 云和县| 永吉县| 循化| 龙井市| 庆云县| 福安市| 奉新县| 连平县| 陆良县| 武隆县| 德州市| 上饶县| 玉田县| 正安县|