同步数据读/写主存储器 [英] Synchronized data read/write to/from main memory

查看:131
本文介绍了同步数据读/写主存储器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个synchronized方法完成时,它是否只将它修改的数据推送到主内存或所有成员变量,类似于同步方法执行时,它是否只读取主内存所需的数据或将它清除缓存中的所有成员变量并从主内存中读取它们的值?例如

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;
    }

}

在上面的代码中假设计算是由threadA执行,getResult由threadB执行。执行compute之后,threadA会用a和b更新主内存,还是会更新a,b,c和d。在执行getResult之前,threadB只从主内存中获取b和c的值,还是清除缓存并获取所有成员变量a,b,c和d的值?

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 ?

推荐答案

synchronized 确保您拥有一致的数据视图。这意味着您将读取最新值,其他缓存将获得最新值。缓存足够聪明,可以通过特殊总线相互通信(不是JLS要求的,但允许的话)。这种总线意味着它不需要触摸主内存就可以获得一致的视图。

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.

这篇关于同步数据读/写主存储器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆