垃圾收集和同步可见性 [英] Garbage collection and synchronized visibility

查看:63
本文介绍了垃圾收集和同步可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have read about marking an object as volatile doesn't guarantee visibility of it's members ( I'm not saying about thread safety just memory visibility , quoting :

JVM仅将对象引用视为易失性,而不是将驻留在堆上的对象数据本身

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. 在对象上使用易失性的情况下,对象引用也会更改.如果旧的引用被缓存在一个线程的CPU缓存中会怎样? GC可以保持它的生命力吗?
  1. The synchronize will ensure the visibility of the members (on the same lock object) in case they have been edited. Is that because the happens-before at the end (release) of the lock which makes the actions visible to the other thread?
  2. In case of using volatile on the object, and the object reference change. what happens if the old reference is cached in one thread CPU cache? Will the GC keep it alive?

示例代码:

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关系线程和读取线程.
  1. Yes, happens-before relationship will gurantees that. While volatile keyword also builds happens-before relationship between the write thread and the read thread.

使用易失性变量可降低内存一致性的风险 错误,因为任何对volatile变量的写入都会建立一个 发生于事前的关系以及随后的相同阅读 变量.

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.

  1. java语言规范没有提及它,也没有提及有关如何实现volatile的任何特定机制.所以我想这取决于特定的JVM.

这篇关于垃圾收集和同步可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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