【发布时间】:2014-04-12 08:46:12
【问题描述】:
我想用java周期性地从mysql加载一些系统信息,大概10秒一次,用一个线程完成,同时有多个线程需要读取这些信息,有两种情况:
1、声明一个public static映射:
public volatile static Map<String, String> info = new HashMap<String, String>();
// Context.java
// start a thread to load from mysql
private void load() {
new Thread(new Runnable() {
while(true) {
// return a map
info = loadFromDB(); // every time a new map
Thread.sleep(5 * 1000); // sleep 5 seconds
}
}).start();
}
// mutiple threads call this function
public String getConfig(String key) {
return Context.map.get(key);
}
正如代码所示,每次线程从db加载信息时,都是一个新的映射,我不需要更改map的内容,这个线程安全吗?
2,也许我想要一个有序的map,而读取线程需要获取map中的max key,这种情况,我应该使用TreeMap还是ConcurrentSkipListMap?
更新
将Map 信息更改为volatile 以避免使用cpu 进行缓存。
【问题讨论】:
-
我认为这种情况有点不同。
-
摘自HashMap -
If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally的文档。因此,我认为使用ConcurrentHashMap是您最好的选择。 -
但是没有线程尝试修改地图,只是改变了参考,所以我还是一头雾水。
-
绝对!我完全同意您的看法,因为您不会更新从外部任何地方的数据库加载的地图,并且仅将其用于阅读目的。
标签: java mysql multithreading concurrency concurrentmodification