最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

同步进入、退出和易失性读写时的缓存刷新

网站源码admin25浏览0评论
本文介绍了同步进入、退出和易失性读写时的缓存刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

当同步块执行完成时,所有处理器缓存都会被刷新,还是只有同步语句作用于其上的对象才会被刷新?在下面的例子中,当线程完成method2的执行时,obj2的数据是否也刷新到主内存?

When synchronized block execution is completed all the processor cache is flushed or only that object on which synchronized statement acted on will be flushed? In the below example when thread finished execution of method2 does data of obj2 is also flushed to the main memory?

class cls1 {
    int x=10;
}

class cls2{
    int y=10;
}

class cls3{
    cls1 obj1;
    cls2 obj2;
    public void method2(){
        obj2.y=10;
        synchronized(obj1){
            obj1.x=30;
        }
    }

    public static void main(String[] args) {
        final cls3 obj3 = new cls3();

        Thread thread1 = new Thread(){
            public void run(){
                obj3.method2();
            }
        };
        Thread thread2 = new Thread(){
            public void run(){
                System.out.println(obj3.obj1.x);
            }
        };
    }
}

推荐答案

只有当另一个线程也在第一个线程更新内容的锁上同步时,才会在关系建立之前发生.

A happens before relation is established only when the other thread also synchronizes on the lock using which the first thread updated the contents.

在此示例中,线程 B 在获取同一对象 M 上的锁后,将能够看到在同步块之前和期间所做的所有更改.但请注意,必须获得锁才能happens-before 关系发生.

In this example Thread B after acquiring the lock on same object M, it will be able to see all the changes that were made before and during the synchronized block. But mind that the lock must be acquired for happens-before relationship to occur.

在您的示例中,因为 System.out.println(obj3.obj1.x); 未打印在同步块内,因此不能保证之前发生.

In your example because System.out.println(obj3.obj1.x); is not printed inside a synchronized block, it does not guarantee happens before.

参考文献:

http://www.ibm/developerworks/library/j-jtp03304/

Peter 使用 volatile 和 synchronized 时刷新或发布到各个线程的内存范围是多少?

这篇关于同步进入、退出和易失性读写时的缓存刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

发布评论

评论列表(0)

  1. 暂无评论