【发布时间】:2020-07-28 15:52:01
【问题描述】:
static volatile Map currentMap = null; // this must be volatile
static Object lockbox = new Object();
public static void buildNewMap() { // this is called by the producer
Map newMap = new HashMap(); // when the data needs to be updated
synchronized (lockbox) { // this must be synchronized because
// of the Java memory model
// .. do stuff to put things in newMap
newMap.put(....);
newMap.put(....);
}
/* After the above synchronization block, everything that is in the HashMap is
visible outside this thread */
/* Now make the updated set of values available to the consumer threads.
As long as this write operation can complete without being interrupted,
and is guaranteed to be written to shared memory, and the consumer can
live with the out of date information temporarily, this should work fine */
currentMap = newMap;
}
public static Object getFromCurrentMap(Object key) {
Map m = null;
Object result = null;
m = currentMap; // no locking around this is required
if (m != null) { // should only be null during initialization
Object result = m.get(key); // get on a HashMap is not synchronized
// Do any additional processing needed using the result
}
return(result);
}
这是本文https://www.ibm.com/developerworks/library/j-hashmap/index.html的代码示例 我仍然不明白为什么我们需要在 buildNewMap 方法中使用同步块。除了 currentMap = newMap;做。 当我们在 m = currentMap; 处读取地图参考时;我们依赖 volatile 读写,读取线程甚至不知道生产者线程中的同步......
【问题讨论】:
标签: java concurrency synchronized