正在 64 位 VM 上编写参考原子
java 内存模型要求写入 int
是原子的:也就是说,如果您在一个线程中向其写入一个值(由 4 个字节组成)并在另一个线程中读取它,您将获得所有字节或无,但绝不会有 2 个新字节和 2 个旧字节等。
对于 long
不保证这一点。在这里,将 0x1122334455667788
写入之前保存 0
的变量可能会导致另一个线程读取 0x112233440000000
或 0x0000000055667788
。
现在,规范不强制要求对象引用必须是 int 或 long 大小。出于类型安全原因,我怀疑它们保证以原子方式写入,但在 64 位 VM 上,这些引用可能是很好的 64 位值(仅是内存地址)。
现在我的问题是:
- 是否有任何内存模型规格涵盖此内容(我还没有找到)?
- 长写入在 64 位 VM 上是否具有原子性?
- VM 是否强制将引用映射到 32 位?
问候, 史蒂芬
The java memory model mandates that writing a int
is atomic: That is, if you write a value to it (consisting of 4 bytes) in one thread and read it in another, you will get all bytes or none, but never 2 new bytes and 2 old bytes or such.
This is not guaranteed for long
. Here, writing 0x1122334455667788
to a variable holding 0
before could result in another thread reading 0x112233440000000
or 0x0000000055667788
.
Now the specification does not mandate object references to be either int or long-sized. For type safety reasons I suspect they are guaranteed to be written atomically, but on a 64bit VM these references could be very well 64bit values (merely memory addresses).
Now here are my questions:
- Are there any memory model specs covering this (that I haven't found)?
- Are long-writes suspect to be atomic on 64bit VMs?
- Are VMs forced to map references to 32bit?
Regards,
Steffen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
读/写引用始终是原子的
请参阅 JLS 部分17.7:double和long的非原子处理
(强调)
AtomicReference
如果您想在旧值和新值之间进行协调,或者想要特定记忆效应,使用类
AtomicReference
。例如,
AtomicReference::getAndSet
返回旧值,同时以原子方式设置新值,从而消除了另一个线程干预两个步骤之间的任何机会。使用易失性
内存语义。Reading/writing references always atomic
See JLS section 17.7: Non-atomic Treatment of double and long
(Emphasis added)
AtomicReference
If you want to coordinate between old and new values, or want specific memory effects, use the class
AtomicReference
.For example,
AtomicReference::getAndSet
returns the old value while setting the new value atomically, eliminating any chance of another thread having intervened between the two steps. Usesvolatile
memory semantics.