java原子性变量,Java中参考变量的读写原子性

First the quote from

From JLS 8 Sec 17.7

Writes to and reads of references are always atomic, regardless of

whether they are implemented as 32-bit or 64-bit values.

Here is the scenario that confuses me, given Employee class and a method within this class called calculate which returns a reference to an instance of Employee.

Employee emp = calculate();

When a write to variable is atomic, it means that no other thread can access that variable until the atomic operation is done, and in the given assignment example, does the atomicity of the write include the evaluation of the right side of the assignment (however complex), OR does the atomicity of the write only apply to when the right side is fully evaluated, and then the write operation is actually done.

In other words, I'm asking if during the evaluation of calculate(), the access to the emp variable is denied for other threads, or is it denied only when the right side of the assignment is fully evaluated and the write operation to emp start?

Sorry for the long story, and

Thanks a lot!

解决方案

The atomicity of a write means that at the time you have the value ready to store, the write will be done in a way such that every thread either (1) reads the previous value or (2) reads the new value, but never something corrupted. In your case, the logic to execute the statement

emp = calcluate();

can be broken down into two steps:

Call the calcluate method and obtain a value; let's call it val.

Atomically write val into emp.

This means that if you try to read emp while the calculate function is still going (or, in the narrow time band between when it returns and the value hasn't been written yet), you will just get whatever value happens to already be in emp. The other threads will not be blocked from reading it. If you want to do that, you'll need to use some explicit synchronization.

(As a note - atomicity does not mean "all other threads will be blocked until the value is ready." It means "all other threads will either see the state purely before the operation is done or purely after the operation is done, but nothing else.")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值