Java中原语的同时更新
我正在解决多线程环境中答案的某些下限的迭代计算问题。
在计算过程中,可能会出现多个线程尝试更新公共基元变量的情况。对我来说,其中哪一个会成功地写出它的价值,哪一个会失败并不重要。
我担心的唯一问题是,是否有可能其中一个线程会写入原语的一部分(例如第一个字节),而另一个线程会写入另一部分(例如最后一个字节),因此该原语的值将是不是线程试图写入的内容。
非常感谢官方文献的链接。
提前致谢。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引用 Java 语言规范:
写入其他原语始终是原子的。但是,如果它们没有声明为
易失性
,则更新可能在任意长时间内对其他线程不可见。Citing the Java Language Specification:
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.java.util.concurrent.atomic.Atomic*
类很好地解决了这个问题。正如 Michael 指出的那样,对非 64 位原语的写入是原子的,但其他线程可能看不到新值 - 可能永远看不到。您可能不关心计算过程中的陈旧读取,但无法保证读取最终解决方案的线程将看到正确的值,除非您使原语为易失性,同步对其的访问,或使用
AtomicWhatever< /代码>。
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
.