Several days before, I raised a question to ask how using the keyword 'volatile' and I got the answer. Here I'd like to thanks again for the people who helped me. However, a new question rose in my mind about JMM that is currently I know there are main memory and thread own separate cache memory (maybe there are more professional terms for them), now I want to know what is stored in thread cache memory, the copy of shared object reference (the copy of object address) or the copy of shared object? For example, I declare an object B b = new B(); and b can be accessed by two threads then when b is accessed by the thread is the object reference b is copied and stored in thread own cache memory or is the object which b points to is copied and stored in thread own cache memory? Thanks.
3 Answers
Anything that be accessed by more than one thread could be in the "thread cache". That includes references if they are part of objects. It won't include references held in local variables as they are on the stack and can't be accessed from other threads.
So the answer is really "both".
8 Comments
public class Test { public B b = new B(); public static void main(String[] args) { new Thread() { public void run() { b.setName("test1"); } }.start(); // thread 1 new Thread() { public void run() { b.setName("test2"); } }.start(); // thread 2 } } When thread1 and thread2 access b, do they cache both the copy of reference b and the copy of object? And so the copy b reference points to the copy object but not the orignal one?Generally, you don't need to know when or where a reference is stored. Memory is not just two tiered, its much more complicated than that. From top to bottom you have.
registers
L1 cache
L2 cache
L3 cache
local main memory
nonlocal main memory
swap space.
local main memory is memory local to your CPU. You can have memory local to another CPU. So to perform
B b = new B();
It has to allocate some memory which usually comes from the TLAB (Thread Local Allocation Buffer) This memory space is usually somewhere between L1 to local main memory. There can be copies at all levels. However the reference has to be in a register so it can be assigned to the local variable. It might be saved to the stack and into memory, or it might not.
Even within the CPU, "registers" is a broad category. How a CPU accesses and writes to memory can be surprising complex topic as it can have a big impact on performance.