线程安全设置变量(Java)? [英] Thread-safe setting of a variable (Java)?

查看:119
本文介绍了线程安全设置变量(Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

public class FooBar { 

public static volatile ConcurrentHashMap myConfigData  = new ConcurrentHashMap();      

}

public class UpdaterThread implements Runnable { 

run {

//Query the Data from the DB and Update the FooBar config Data
FooBar.myConfigData = ConfigDataDAO.getLatestConfigFromDB();
}
}

Thread-Class将定期更新myConfigData会员变量(每5分钟通过执行官)。 myConfigData的设置是在外部线程threadafe(原子)中,还是我必须将每个Read和Write操作同步到myConfigData变量?

The Thread-Class will update the myConfigData Membervariable regularly (via an Executor every 5 minutes). Is the setting of of myConfigData in the "external" Thread threadsafe (atomic), or do I have to synchronize every Read and Write operation to the myConfigData Variable?

编辑:问题不在于ConcurrentHashMap是线程安全的(它是根据javadoc)而是在myConfigData Member变量中设置ConcurrentHashMap本身。这个变量可能被几个线程一次读取和写入,所以问题是设置是否是原子的。我认为这可以概括为Java引用变量的设置是否为原子?。

The question is not whether ConcurrentHashMap is threadsafe (it is according to javadoc) but rather the setting of the ConcurrentHashMap itself in the myConfigData Member variable. This variable might be read and written "at once" by several threads so the question is whether the setting is atomic or not. I think this can be generalized to "Is the setting of a Java reference variable atomic or not?".

(我也使它变得不稳定。这是一个不同的问题,与原子性无关 - 我的问题 - 而是其他线程中的可见性和之前发生的关系。)

(I also made it volatile. This is a different issue and has nothing to do with atomicity - my question - but rather "visibility in other threads" and the happens-before relationship.)

推荐答案

更换参考文献是安全的。请参阅 Java语言规范

Replacing references is safe. See Java language Specification:


当线程使用变量的值时,它获得的值实际上是由该线程或其他一些线程存储到变量中的值线。即使程序不包含正确同步的代码,也是如此。例如,如果两个线程将对不同对象的引用存储到同一引用值中,则该变量随后将包含对一个对象或另一个对象的引用,而不是对某个其他对象的引用或损坏的引用值。 (长值和双值有一个特殊例外;见§17.4。)

When a thread uses the value of a variable, the value it obtains is in fact a value stored into the variable by that thread or by some other thread. This is true even if the program does not contain code for proper synchronization. For example, if two threads store references to different objects into the same reference value, the variable will subsequently contain a reference to one object or the other, not a reference to some other object or a corrupted reference value. (There is a special exception for long and double values; see §17.4.)

这篇关于线程安全设置变量(Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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