Java中参考变量的读写原子性 [英] Atomicity of Reads and Writes for Reference Variables in Java

查看:88
本文介绍了Java中参考变量的读写原子性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先从

First the quote from From JLS 8 Sec 17.7


引用的写入和读取始终是原子的,而与
无关不管它们是实现为32位还是64位值。

Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values.

在这种情况下,给定Employee类和

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.

换句话说,我问的是在评估 calculate(),则对其他线程拒绝访问 emp 变量,或者仅当完全评估了赋值的右侧并且对 emp 开始吗?

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!

推荐答案

写入的原子性意味着在您准备好存储值时,写入将完成以这样的方式ead(1)读取前一个值,或者(2)读取新值,但绝不会损坏。在您的情况下,执行语句的逻辑

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();

可以分为两步:


  1. 调用 calcluate 方法并获得一个值;我们称它为 val

  2. val 原子写入 emp

  1. Call the calcluate method and obtain a value; let's call it val.
  2. Atomically write val into emp.

这意味着如果您尝试阅读 emp calculate 函数仍在运行(或者,在返回和尚未写入值之间的狭窄时间段内),只会得到 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.")

这篇关于Java中参考变量的读写原子性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆