Java 8 Stream并行处理期间所有处理器核心的缓存是否同步?

Do the caches of all processor's cores are synchronized during Java 8 Stream parallel processing?

如果我们在多核处理器上工作,如果任务被划分并分配给不同的内核来处理,我们需要这些内核的缓存同步。 Java 8 Stream 库是如何做到这一点的? Java 8 流并行处理期间所有处理器内核的缓存是否同步?

这是Java Memory Model的保证之一。只要您的程序正确同步(通过 synchronizedLock 或其他形式的同步),您的共享内存将对所有线程可见。

并不是说缓存会 "synchronized," 而是在访问正确同步的变量之前重新加载它们,并在写入正确同步的变量时刷新它们。

JLS§17.4.3

Within a sequentially consistent execution, there is a total order over all individual actions (such as reads and writes) which is consistent with the order of the program, and each individual action is atomic and is immediately visible to every thread.


JLS§17.3

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.