本文介绍了线程安全设置变量(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.)

推荐答案

更换参考文献是安全的。请参阅:

Replacing references is safe. See Java language Specification:

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

07-29 19:32
查看更多