-
Notifications
You must be signed in to change notification settings - Fork 7.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Java 多线程三大核心 发现的问题 #65
Comments
@Mr-GaoSai 多谢提醒,已经修复。 见 #68 |
font{
line-height: 1.6;
}
ul,ol{
padding-left: 20px;
list-style-position: inside;
}
但是,在双重检查锁的单例模式这部分,却说 “这里的 volatile 关键字主要是为了防止指令重排。”我们从代码里可以看到,singleton = new Singleton();这一句,是在synchronized修饰下的。所以,如果synchronized能保证有序性,为什么还需要volatile呢所以我这里说的 volatile 的作用是防止指令重排,并不是保证有序,这个没问题啊。这个问题也讨论过几次了,可以参考这个链接:CyC2018/CS-Notes#352
crossoverJie
公众号:crossoverJie
个人博客:https://crossoverjie.top
个人主页:https://github.com/crossoverJie
签名由
网易邮箱大师
定制
在2019年07月21日 16:23,kratosB<notifications@github.com> 写道:
你好,关于这个问题,我有一个疑问,希望能指教一下,谢谢。
在《Java 多线程三大核心》的有序性部分,有这么一句话 “Java中可以使用 volatile 来保证顺序性,synchronized 和 lock 也可以来保证有序性,和保证原子性的方式一样,通过同一段时间只能一个线程访问来实现的。“ 说明synchronized关键字也能保证有序性。
但是,在双重检查锁的单例模式这部分,却说 “这里的 volatile 关键字主要是为了防止指令重排。”
我们从代码里可以看到,singleton = new Singleton();这一句,是在synchronized修饰下的。所以,如果synchronized能保证有序性,为什么还需要volatile呢?
基于这个疑惑,我在网上找到一个帖子:单例模式中用volatile和synchronized来满足双重检查锁机制。帖子里面说,这里得volatile是为了保证多线程下的可见性。感觉这个帖子里的解释,比较符合我的想法。
如果这个地方没有错,希望你能帮我解答一下。如果这个地方错了,我也很高兴我能为JCSprout出一份力。很喜欢这个项目,希望越来越好。
—You are receiving this because you modified the open/close state.Reply to this email directly, view it on GitHub, or mute the thread.
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
位置:https://github.com/crossoverJie/Java-Interview/blob/master/MD/Threadcore.md#双重检查锁的单例模式
双重检查锁的单例模式这部分
文中写到:有可能第二步在第三步之前被执行就有可能某个线程拿到的单例对象是还没有初始化的,以致于报错。
应该是第三步在第二步之前执行,导致其他线程拿到单利对象还没有初始化
The text was updated successfully, but these errors were encountered: