问题
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!
回答1:
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 itval
. - Atomically write
val
intoemp
.
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.")
来源:https://stackoverflow.com/questions/40774010/atomicity-of-reads-and-writes-for-reference-variables-in-java