I'm trying to understand the Java memory model and threads. As far as I understand, each thread has a local copy of the "main" memory. So if one thread tries to change an int
variable, for example, of some object, it caches the int
variable and if it changes it, other thread might not see the change.
But what if threads cache some object instead of int? What threads cache it in this case? If a thread caches a reference to an object any change to the state of the object are not visible to other threads? Why?
The memory model stipulates that changes to the values of shared variables only need to be made visible to other threads when such a synchronization barrier is reached. Moreover, the entire notion of a race condition is defined over the order of operations with respect to these memory barriers.
In Java, threads doesn't cache any object or variable, they just have a reference to an instance of an object. Talking about thread cache memory is more like talking about operative systems threads...
2. Stack Memory in Java. Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap.
The Java memory model describes how threads in the Java programming language interact through memory. Together with the description of single-threaded execution of code, the memory model provides the semantics of the Java programming language.
CPU have different level caches L1, L2, L3. Every CPU (and also /may CPU Core) has own cache. This caches store minimal set of main memory (RAM) for performance.
_______________ ______________ | CPU 1 | | CPU 2 | | _________ | | _________ | | | Level 1 | | | | Level 1 | | | | Cache | | | | Cache | | | | | | | | | | | |_________| | | |_________| | |_______________| |______________| | | | | | | | | _|_|______________|_|__ | | | MAIN MEMORY | |_______________________| Time Command CPU 1 (Cache) CPU 2 (Cache) Main Memory ------- ---------- ---------------- -------------- ------------- 1 --- --- --- x = 10 2 Read x (on cpu1) x = 10 --- x = 10 3 Write x <--20 (on cpu1) x = 20 --- x = 10 4 Read x (on cpu2) x = 20 x = 10 x = 10 5 put cache to Main mem x = 20 x = 10 x = 20
For example, Above execution order, x value is wrong on CPU2. x value already changed by CPU1. If x variable is defined as volatile, all write operation reflect to main memory instantly.
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