多个字段:volatile或AtomicReference? [英] multiple fields: volatile or AtomicReference?

查看:447
本文介绍了多个字段:volatile或AtomicReference?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将线程之间的访问同步到共享对象,其状态由多个字段组成。说:

I have to synchronize access between threads to a shared object, whose state consists of several fields. Say:

class Shared{
String a; Integer b;
//constructor, getters and setters
....
}

我可能有很多线程读取这些对象,执行

I have possibly many threads reading this objects, doing

//readers
shared.getA();
shared.getB();

并且只有一个线程将在某一时刻写入:

and only one thread that will write at a certain point:

//writer
shared.setA("state");
shared.setB(1);

现在我的问题是如何确保读取线程不会找到共享对象处于不一致状态。

now my question is how to ensure that reading threads won't find the shared object in an inconsistent state.

我读了很多答案说,线程之间的一致性 volatile 是解决方案,但我不确定如何在多个领域工作。例如,是否足够了?

I read many answers saying that for consistency between threads volatile is the solution,but I'm not sure how it works on multiple fields. E.g., is that enough?

volatile  String a; volatile Integer b;

另一个解决方案是使共享对象不可变,并使用AtomicReference,Eg,

Another solution would be to make the shared object immutable and use AtomicReference, E.g.,

AtomicReference<Shared> shared = ....

,然后作者将交换引用:

and then the writer will just swap the reference:

Shared prev = shared.get(); 
Shared newValue = new Shared("state",1);
while (!shared.compareAndSet(prev, newValue)) 

这种方法是否正确?感谢!

Is that approach correct? thanks!

更新在我的设置中,共享对象是从 ConcurrentHashMap检索的< Id,Shared> ,所以评论同意要走的方式是使用不可变的方法或通过同步共享的更新在一起。然而,为了完整性,将很好地知道是否使用 ConcurrentHashMap 的解决方案是可行的或错误的或仅仅是多余的。任何人都可以解释?谢谢!

Update In my setting the Shared objects are retrieved from a ConcurrentHashMap<Id,Shared>, so the comments agree that the way to go is either using the immutable approach or via synchronizing the updates on shared all together. However, for completeness would be nice to know whether the solution above with the ConcurrentHashMap<Id,AtomicReference<Shared>> is viable or wrong or just superfluous. Anyone can explain? thanks!

推荐答案

首先你应该使 Shared immutable: / p>

First of all you should make Shared immutable:

class Shared{
   private final String a; 
   private final int b;
   //constructor, getters and NO setters
}

只有一个写者,你可以安全地使用volatile,在AtomicRefference中没有必要。在信息更新的时候,不应该修改旧的对象,而是创建一个新的对象并分配给一个不稳定的参数。

And if you have only one writer you can safely use volatile, there is no need in AtomicRefference. At the point where information is updated old object should not be modified, but rather a new created and assigned to a volatile refference.

这篇关于多个字段:volatile或AtomicReference?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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