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

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.

主站蜘蛛池模板: 南安市| 绩溪县| 翁牛特旗| 奎屯市| 玛纳斯县| 嘉禾县| 天津市| 鲁甸县| 天峨县| 明光市| 福清市| 专栏| 邻水| 临颍县| 嘉黎县| 旬阳县| 宁明县| 航空| 岳池县| 博客| 长兴县| 布拖县| 衡阳县| 论坛| 武陟县| 阜阳市| 西华县| 视频| 灵丘县| 隆安县| 万山特区| 龙胜| 四子王旗| 贵港市| 紫金县| 格尔木市| 府谷县| 通河县| 松溪县| 余干县| 辛集市|