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

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.

主站蜘蛛池模板: 岫岩| 富川| 平利县| 深水埗区| 东平县| 汤阴县| 乾安县| 通辽市| 新沂市| 绥芬河市| 长春市| 江城| 会东县| 长岭县| 凤翔县| 满城县| 昭苏县| 区。| 县级市| 黄冈市| 弥渡县| 淳安县| 镇平县| 庆元县| 工布江达县| 汶上县| 西青区| 新巴尔虎右旗| 金乡县| 湾仔区| 衡山县| 交口县| 浦江县| 高平市| 大荔县| 南陵县| 威信县| 泗水县| 吴江市| 桃江县| 阿合奇县|