Java中的可见性问题是由JVM还是硬件引起的?

发布于 2024-11-30 00:08:32 字数 300 浏览 1 评论 0原文

以前我认为可见性问题是由CPU Cache 引起的性能问题。

但我看到这篇文章: http://www.ibm.com /developerworks/java/library/j-5things15/index.html

在第3.易失性变量段落中,它告诉Thread持有缓存,听起来缓存是由JVM引起的。

答案是什么? JVM 还是硬件?

Previously I think the Visibility Problem is cause by CPU Cache for performance.

But I saw this article: http://www.ibm.com/developerworks/java/library/j-5things15/index.html

In the paragraph 3. Volatile variables, it tells that Thread holds the cache, sounds like the cache is caused by JVM.

What's the answer? JVM or Hardware?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许你一世情深 2024-12-07 00:08:32

JVM 给了你一些弱保证。编译器和硬件会给你带来问题。 :-)

当线程读取变量时,它不一定从内存中获取最新值。处理器可能会返回缓存的值。此外,即使程序员编写的代码中首先写入然后读取变量,只要不更改程序语义,编译器也可能会对语句进行重新排序。处理器和编译器为了性能优化而这样做是很常见的。因此,线程可能看不到它期望看到的值。这可能会导致并发程序中的错误难以修复。

大多数程序员都熟悉这样一个事实:进入同步块意味着获得监视器上的锁,以确保没有其他线程可以进入同步块。不太熟悉但同样重要的事实是

(1) 获取锁并进入同步块会强制线程刷新内存中的数据。
(2) 退出同步块时,写入的数据将刷新到内存。
http://www.javacodegeeks.com/ 2011/02/java-memory-model-quick-overview-and.html

另请参阅 JSR 133(Java 内存模型和线程规范修订版)http://jcp.org/en/jsr/detail?id=133 它与 JDK 1.5 一起发布。

JVM gives you some weak guarantees. Compiler and Hardware cause you problems. :-)

When a thread reads a variable, it is not necessarily getting the latest value from memory. The processor might return a cached value. Additionally, even though the programmer authored code where a variable is first written and later read, the compiler might reorder the statements as long as it does not change the program semantics. It is quite common for processors and compilers to do this for performance optimization. As a result, a thread might not see the values it expects to see. This can result in hard to fix bugs in concurrent programs.

Most programmers are familiar with the fact that entering a synchronized block means obtaining a lock on a monitor that ensures that no other thread can enter the synchronized block. Less familiar but equally important are the facts that

(1) Acquiring a lock and entering a synchronized block forces the thread to refresh data from memory.
(2) Upon exiting the synchronized block, data written is flushed to memory.
http://www.javacodegeeks.com/2011/02/java-memory-model-quick-overview-and.html

See also JSR 133 (Java Memory Model and Thread Specification Revision) http://jcp.org/en/jsr/detail?id=133 It was released with JDK 1.5.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文