gpt4 book ai didi

java - 垃圾收集和同步可见性

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:34 25 4
gpt4 key购买 nike

我已经读过有关将对象标记为 volatile 并不能保证其成员的可见性的内容(我不是说线程安全只是内存可见性,引用:

only the object reference will be considered to be volatile by the JVM and not the object data itself which will reside on the heap

我的问题:

  1. 同步将确保成员(在同一锁定对象上)在被编辑时的可见性。这是因为在锁结束(释放)之前发生使得其他线程可以看到操作吗?
  2. 如果在对象上使用 volatile,并且对象引用发生变化。如果旧引用缓存在一个线程 CPU 缓存中会发生什么? GC 会让它保持活力吗?

示例代码:

class Test{
volatile Data data;

}

Class Data{
int x;
int y;
}


data= new Data(); // happens-before relationship only on creation

//writer
Thread writerThread = new Thread(() -> {
data.setX(a);
data.setY(b);
});


//reader
Thread readerThread = new Thread(() -> {

// read here is not guaranteed visibility, x,y not volatile
int x = data.getX();
int y = data.getY();
});

最佳答案

  1. 是的,happens-before 关系将保证这一点。而volatile关键字还在写入线程和读取线程之间建立happens-before关系。

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

  • java语言规范中没有提到它,也没有提到任何关于如何实现 volatile 的具体机制。所以我猜这取决于具体的JVM。
  • 关于java - 垃圾收集和同步可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791805/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com