java - Java中原语的同时更新

标签 java multithreading primitive

我正在解决多线程环境中答案的某些下限的迭代计算问题。

在计算过程中,可能会有多个线程尝试更新公共(public)基元变量。对我来说,其中哪一个会成功地写出它的值(value),哪一个会失败并不重要。

我担心的唯一问题是,是否有可能其中一个线程会写入原语的一部分(例如第一个字节),而另一个线程会写入另一部分(例如最后一个字节),因此该线程的值原语将不是线程试图写入的内容。

非常感谢官方文献的链接。

提前致谢。

最佳答案

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.

引用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.

写入其他原语始终是原子的。但是,如果它们未声明为 volatile ,则更新可能在任意长时间内对其他线程不可见。

关于java - Java中原语的同时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4179540/

相关文章:

用于基元的 Java vector 或 ArrayList

java - 使用spring data jpa设计父子关系的层次结构

java - 为什么我无法在 Android 中创建 *.txt 文件?

java - 每秒检查一次时间

c - 使用 OpenMP 进行数组缩减导致 "user defined reduction not found for"

java - Java 中 native 类型(基元)的泛型(或替代方法)

c# - C# 中的自定义原语?

java.io.InvalidClassException : local class incompatible - Apache Spark Submit issue for more than one worker

java - 如何使图像相对于其框架缩放(ImageJ)

java - 检测当前线程是否为 ExecutorService 线程