I want to load some system information from mysql with java periodically, maybe 10 seconds once, and use one thread to finish this, at the same time, there are mutiple threads need to read this information, there are two situatons :
1, declare a public static
map :
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);
}
Just as the code shows, every time the thread load info from db, it's a new map, and I needn't change the map
content, is this thread safe?
2, maybe I want a sorted map, and the read threads need to fetch the max key in the map, in this situation, should I use TreeMap
or ConcurrentSkipListMap
?
Update
change the Map
info with volatile
to avoid cache with cpu.