• 请不要在回答技术问题时复制粘贴 AI 生成的内容
tuzhenyu
V2EX  ›  程序员

Java 关键字 synchronized 能不能禁止指令重排序?

  •  
  •   tuzhenyu · Oct 14, 2017 · 7091 views
    This topic created in 3309 days ago, the information mentioned may be changed or developed.

    在一些书上和博客上看到说 synchronized 有禁止指令重排序的作用,如果这样的话单例模式的双重检查锁模式就不需要 volatile 修饰了吧?求助大佬...

    12 replies  •  2017-10-16 13:05:38 +08:00
    sagaxu
    sagaxu
    Oct 14, 2017 via Android
    1
    理解有误
    juxingzhutou
    juxingzhutou
    Oct 14, 2017
    2
    synchronized 都已经加锁了你还要双重锁检查干嘛?
    tuzhenyu
    tuzhenyu
    OP
    Oct 14, 2017
    3
    @sagaxu 是 synchronized 没有禁止指令重排序的作用吗?
    tuzhenyu
    tuzhenyu
    OP
    Oct 14, 2017
    4
    @juxingzhutou   单例模式的双重检查是双重非空检查,只加了一个 synchronized 锁

    public class DoubleCheckedLocking {
    private static Instance instance;

    public static Instance getInstance() {
    if (instance == null) {
    synchronized (DoubleCheckedLocking.class) {
    if (instance == null)
    instance = new Instance();
    }
    }
    return instance;
    }
    }
    iEverX
    iEverX
    Oct 14, 2017
    5
    没有,需要加 volatile 的
    juxingzhutou
    juxingzhutou
    Oct 14, 2017
    6
    @tuzhenyu 你这样写的话 synchronized 并不能保证在它之前的非空判断的“顺序”问题,根据 JSR-133 定义的 JMM,synchronized 的加锁和解锁之间能够有确定的顺序,但是多个线程下 synchronized 之前的非空判断之间并不能保证顺序。所以需要用 volatile 来保证非空判断之间的 happens-before 关系。

    有兴趣的话建议你完整地看一下 JSR-133 相关的文章。
    tuzhenyu
    tuzhenyu
    OP
    Oct 14, 2017
    7
    @juxingzhutou 好的 谢谢!
    tuzhenyu
    tuzhenyu
    OP
    Oct 14, 2017
    8
    @iEverX 谢谢!
    NUT
    NUT
    Oct 15, 2017
    9
    @juxingzhutou 正解。
    @tuzhenyu JMM 会保证程序在允许范围内执行指令混排,所以在视觉上会给人造成顺序执行的假象。除了用 syn 意外还能使用 乐观锁的 思想来处理。看着这个 访问 http://www.hollischuang.com/archives/1866
    XiLemon
    XiLemon
    Oct 15, 2017 via iPhone
    10
    楼主搜一搜陈皓和 wuchong 的单例模式正确写法的 blog
    hantsy
    hantsy
    Oct 16, 2017
    11
    来看看 Bob Lee ( Guice 作者) 的双检模型:
    http://blog.crazybob.org/2007/01/lazy-loading-singletons.html
    ppaapc
    ppaapc
    Oct 16, 2017
    12
    加了 synchronized 关键字还需要禁止指令重排序干嘛
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4843 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 07:48 · PVG 15:48 · LAX 23:48 · JFK 02:48
    ♥ Do have faith in what you're doing.