开发者

simultaneous update of primitives in Java

开发者 https://www.devze.com 2023-01-24 20:42 出处:网络
I\'m solving a problem of iterative calculation of some lower bound of the answer in a multi-threading environment.

I'm solving a problem of iterative calculation of some lower bound of the answer in a multi-threading environment.

During the calculation, it could happen that number of threads would try to update a common primitive variable. It 开发者_JAVA技巧doesn't matters for me which one of them would succeed to write it's value and which would fail.

The only problem I'm bothered about is if it possible that one of the threads would write part of the primitive (e.g. first bytes) and another would write another part (e.g. last bytes) and as a result the value of that primitive would be non of what the threads were trying to write.

A link to an official literature would be very appreciated.

Thanks in advance.


The only problem I'm bothered about is if it possible that one of the threads would write part of the primitive (e.g. first bytes) and another would write another part (e.g. last bytes) and as a result the value of that primitive would be non of what the threads were trying to write.

Citing the Java Language Specification:

If a double or long variable is not declared volatile, then for the purposes of load, store, read, and write actions they are treated as if they were two variables of 32 bits each: wherever the rules require one of these actions, two such actions are performed, one for each 32-bit half. The manner in which the 64 bits of a double or long variable are encoded into two 32-bit quantities is implementation-dependent. The load, store, read, and write actions on volatile variables are atomic, even if the type of the variable is double or long.

Writing to other primitives is always atomic. However, if they are not declared volatile then updates may not be visible to other threads for an arbitrarily long time.


The java.util.concurrent.atomic.Atomic* classes solve the problem nicely. As Michael points out, writes to non-64-bit primitives are atomic but other threads may not see the new value - possibly ever.

You may not care about stale reads during computation but there is no way to guarantee that the thread that reads the final solution will see the correct value unless you either make the primitive volatile, synchronize access to it, or use an AtomicWhatever.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号