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

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.

主站蜘蛛池模板: 乳源| 江山市| 维西| 榕江县| 绥滨县| 天全县| 合作市| 大兴区| 德惠市| 孟津县| 大田县| 潢川县| 桐城市| 玉山县| 昂仁县| 定结县| 遂昌县| 莒南县| 瑞安市| 广德县| 凤城市| 定襄县| 达日县| 垫江县| 新昌县| 紫云| 海安县| 定西市| 苍溪县| 赤城县| 资中县| 奉贤区| 太仆寺旗| 万荣县| 云霄县| 岐山县| 长宁区| 喜德县| 林西县| 郸城县| 郁南县|