双重检查锁定的无序写入 [英] Out-of-order writes for Double-checked locking

查看:125
本文介绍了双重检查锁定的无序写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在针对双重检查锁定方案的无序写入提到的示例中(参考:
IBM文章& 维基百科文章

In the examples mentioned for Out-of-order writes for double-checked locking scenarios (ref: IBM article & Wikipedia Article)

在构造函数完全初始化之前,我无法理解为什么Thread1会在同步块中出现的简单原因。根据我的理解,创建new和调用构造函数应该按顺序执行,同步锁不应该发布,直到所有工作都没有完成。

I could not understand the simple reason of why Thread1 would come of out synchronized block before the constructor is fully initialized. As per my understanding, creating "new" and the calling constructor should execute in-sequence and the synchronized lock should not be release till all the work in not completed.

请让我知道我在这里缺少什么。

Please let me know what I am missing here.

推荐答案

构造函数可以完成 - 但这并不意味着所有的写入在其他线程中可以看到该构造函数中涉及的内容。令人讨厌的情况是,当对象的内容变得可见之前,引用对其他线程可见(因此它们开始使用它)。

The constructor can have completed - but that doesn't mean that all the writes involved within that constructor have been made visible to other threads. The nasty situation is when the reference becomes visible to other threads (so they start using it) before the contents of the object become visible.

您可能会发现 Bill Pugh关于它的文章也有助于解决问题。

You might find Bill Pugh's article on it helps shed a little light, too.

就我个人而言,我只是避免像瘟疫那样双重检查锁定,而不是试图让它全部工作。

Personally I just avoid double-checked locking like the plague, rather than trying to make it all work.

这篇关于双重检查锁定的无序写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆