Java多线程双重加锁可能问题 Possible double check of field

Possible double check of field
This method may contain an instance of double-checked locking. This idiom is not correct according to the semantics of the Java memory model. For more information, see the web page http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.

(指令重排优化导致)

private static ActivityLifeManager sInstance;

public static ActivityLifeManager getInstance() {
    if (sInstance == null) {
        synchronized (ActivityLifeManager.class) {
            if (sInstance == null) {
                sInstance = new ActivityLifeManager();
            }
        }
    }
    return sInstance;
}

双重加锁可能存在的一个问题就是

例如线程1已经分配了地址给instance 但是还没有初始化, 此时线程2 判断intance不是null 直接返回

解决办法1

volatile的一个语义是禁止指令重排序优化,也就保证了instance变量被赋值的时候对象已经是初始化过的,从而避免了上面说到的问题。

image.png

volatile关键字使线程不直接从cpu寄存器读取而是从栈

  /*
  * 为了避免JIT编译器对代码的指令重排序优化,可以使用volatile关键字,
  * 通过这个关键字还可以使该变量不会在多个线程中存在副本,
  * 变量可以看作是直接从主内存中读取,相当于实现了一个轻量级的锁。
  */
 private volatile static ActivityLifeManager sInstance;

public static ActivityLifeManager getInstance() {
    if (sInstance == null) {
        synchronized (ActivityLifeManager.class) {
            if (sInstance == null) {
                sInstance = new ActivityLifeManager();
            }
        }
    }
    return sInstance;
}

解决办法2

public static ActivityLifeManager getInstance() {

    return Singleton.Instance;
}

//同时保证延迟加载和线程安全
private static class Singleton {
    static ActivityLifeManager Instance = new ActivityLifeManager();
}

https://blog.csdn.net/goodlixueyong/article/details/51935526
http://www.importnew.com/16127.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,150评论 0 10
  • 本文致知道我所有缺点,却依旧愿意留在我身边的人。^ω^
    别横着长了好吗阅读 2,812评论 0 0
  • 五年前大概这个时候,正是高中最后冲刺的紧张时刻。我的班主任老师突发奇想,把她座位编到了我的旁边,说是同学之间团结友...
    阿兹特克人阅读 2,981评论 0 1
  • Chrome扩展程序Vimium from my csdn blog 今天在订阅里看到一篇文章介绍vimium的用...
    Amrzs阅读 4,110评论 0 3