Synchronized data read/write to/from main memory

2019-05-07 15:57发布

When a synchronized method is completed, will it push only the data modified by it to main memory, or all the member variables, similarly when a synchronized method executes, will it read only the data it needs from main memory or will it clear all the member variables in the cache and read their values from main memory ? For example

public class SharedData
{

    int a; int b; int c; int d;

    public SharedData()
    {
        a = b = c = d = 10;
    }

    public synchronized void compute()
    {
        a = b * 20;
        b = a + 10;
    }

    public synchronized int getResult()
    {
        return b*c;
    }

}

In the above code assume compute is executed by threadA and getResult is executed by threadB. After the execution of compute, will threadA update main memory with a and b or will it update a,b,c and d. And before executing getResult will threadB get only the value of b and c from main memory or will it clear the cache and fetch values for all member variables a,b,c and d ?

3条回答
神经病院院长
2楼-- · 2019-05-07 16:28

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-07 16:33

I think following thread should answer your question.

Memory effects of synchronization in Java

In practice, the whole cache is not flushed.

查看更多
地球回转人心会变
4楼-- · 2019-05-07 16:34

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.

查看更多
登录 后发表回答