简体   繁体   English

Java单执行线程和CPU缓存

[英]Java single thread of execution and cpu cache

Assume my application has only one thread and the platform on which the application runs has several CPUs. 假设我的应用程序只有一个线程,并且运行该应用程序的平台有多个CPU。 It is possible that the single thread of application at some point of time executes on cpu A , reads the value of property X, modifies its value and the modified value of property X is not committed to main memory, it just resides on cpu registry or cache. 应用程序的单个线程可能在某个时间点在cpu A上执行,读取属性X的值,修改其值并且属性X的修改后的值未提交到主内存,而仅驻留在cpu注册表或缓存。 Then after some time the same thread of application can continue its flow on cpu B, read the value of property X and get the stale value from main memory, as the updated value resides on cpu A registry/cache. 然后,一段时间后,同一应用程序线程可以继续其在cpu B上的流程,读取属性X的值,并从主内存中获取陈旧的值,因为更新后的值位于cpu A注册表/缓存中。

So till now i saw everywhere that such kind of visibility problems occur only in multithreaded apps but seems that in case i have described that is possible as well. 所以直到现在,我到处都看到这种可见性问题仅在多线程应用程序中发生,但是如果我已经描述过,那似乎也是可能的。

Any idea ? 任何想法 ?

The Java language definition says there is a "happens before" relationship between anything that happens earlier in a thread and anything that happens later in the same thread. Java语言定义说,在线程中较早发生的事情与在同一线程中较晚发生的事情之间存在“先发生”关系。 This means that it is the responsibility of the JVM, working with the operating system, to ensure visibility of any data written earlier in the thread to any operations later in the same thread. 这意味着JVM有责任与操作系统一起使用,以确保对线程中较早写入的任何数据可见,对同一线程中较晚进行的任何操作可见。 On most operating systems, I believe this would be handled at the operating system level, by saving register state and flushing cache to memory when a thread is switched out. 我相信在大多数操作系统上,可以通过保存寄存器状态并将线程关闭时将高速缓存刷新到内存中的方式在操作系统级别上进行处理。 In any case, you don't have to worry about it when writing Java code. 无论如何,编写Java代码时都不必担心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM