Synchronized data read/write to/from main memory

邮差的信 提交于 2019-12-05 16:10:54

synchronized ensures you have a consistent view of the data. This means you will read the latest value and other caches will get the latest value. Caches are smart enough to talk to each other via a special bus (not something required by the JLS, but allowed) This bus means that it doesn't have to touch main memory to get a consistent view.

sgp15

I think following thread should answer your question.

Memory effects of synchronization in Java

In practice, the whole cache is not flushed.

1. synchronized keyword on a method or on an atomic statement, will lock the access to the resource that it can modify, by allowing only one thread to gain the lock.

2. Now preventing of caching of values into the variables is done by volatile keyword. Using volatile keyword will ask the JVM to make the thread that access the instance variable to reconcile its copy of the instance variable with the one saved in the memory.

3. Moreover in your above example, if threadA execute the compute(), then threadB canNot access the getResult() method simultaneously, as they both are synchronized methods, and only one thread can have access to the all the synchronized methods of the object, cause its not the method that is locked but the Object. Its like this... Every object has one lock, and the thread which wants to access its synchronized block must get that lock

4. Even every class has a lock, that is used to protect the crucial state of the static variables in the class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!