java双重同步判断_双重检查锁定的Java同步效果?(Java synchronized effect on Double-checked locking?)...

I have read through different articles such as Double-checked locking: Clever, but broken and I understand the reason of why the following code is broken in multi-threading usage.

class SomeClass {

private Resource resource = null;

public Resource getResource() {

if (resource == null) {

synchronized {

if (resource == null)

resource = new Resource();

}

}

return resource;

}

}

However, according to its explanation, when a thread exits a synchronized block, it performs a write barrier -- it must flush out any variables modified in that block to main memory before releasing the lock. Therefore, when Thread A runs into the synchronized block, and then does the following process in order:

Memory for the new Resource object will be allocated;

the constructor for Resource will be called,

initializing the member fields of the new object;

the field resource of SomeClass will be assigned a reference to the newly created object

Finally, before Thread A exits from the synchronized block, it will write its local resource object back to the main memory and then Thread B will read this newly created resource from the main memory once it runs into the synchronized block.

Why Thread B may see these memory operations in a different order than the one Thread A executes? I thought Thread B won't know the resource object is created until Thread A flushes its local memory out to main memory when it exits from the synchronized block because Thread B can only read the resource object from the sharable main memory?

Please correct my understanding....Thank you.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值