I am reading about Java Memory Model in JSR-133 and I cannot understand how this type of behavior is acceptable:

Can somebody please explain it?
The ONLY thing the CPU has to ensure is that the write to X within a thread does NOT affect the subsequent assignment to its associated RX memory location. It says nothing about where it gets the value it's going to write from.
So,
In thread 1, the CPU says
"Ohh, I need to read X", so begins a read operation.
It then says
"And I need to write to X", so then QUEUES the value in a write queue
Thread 2 does the same thing.
"Ohh, I need to read X" and begins the read.
"I need to write to X", and queues the write.
Now we have two waiting reads and two queued writes.
If the CPU architecture says that a read on one core may interrogate another core's write queue, then both cores can read each others outstanding writes to X. Hence you get the two values being pulled across cores, ultimately being assigned to the RX memory location from that thread.
When you place memory barriers in the instruction stream it prevents this type of over eager queued write reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With