I read that JVM achieves the synchronization by copying data of shared variable from the main memory to the thread’s working memory according to this link.
for example, there is a class like this.
class Test {
private Test2 test2 = new Test2();
public void print1() {}
public synchronized void print2() {
test2.print();
}
}
If this Test class is executed in multiple threads and “print2” method is executed in one thread, I think that a lock on Test is acquired by one Thread and other threads have to wait until the lock is released.
Now I have a question. If a lock on Test is acquired by a Thread, does it mean that data of Test and Test2 is copied from the main memory to a thread’s working memory? The reason that I am saying is that “synchronized” keyword is used at instance method level and test2 is a instance variable of Test class.
I am just trying to clarify what is copied from the main memory to a thread’s working memory.
Please correct me if I am wrong.
In brief, all shared variables will be copied (i.e. written from cache to main memory so all threads have the same data) when you use synchronized. When you use volatile, only the one volatile variable is guaranteed to be copied.
I found this to be a helpful resource which touches on the topic.
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html
EDIT: Regarding your comment, section 17.6 of the specification answers your question: