我有一个 HashMap ,其中包含 Link 对象作为值和 Integer 作为键。每隔一秒就会更新一次,同时从某个不同线程中的其他类访问它。我想在更新值部分(API 响应后的链接对象)时使 hashmap 不可访问,并在更新完成后使其可访问。什么是最好的方法来做到这一点。
class Link{
int id;
int currentBWidth;
//getter and setter
}
public class Cache implements Runnable {
public static HashMap<Integer, Link> linkDetailsMap;//accessed by some other class
static {
initMap();
}
private static void initMap() {
linkDetailsMap = new HashMap<Integer, Link>(667);//needed a hashmap
with fixed size 500
for (int count = 0; count < 500; count++) {
Link link = new Link();
link.setLinkId(count);
link.setCurrentBWidth(count);
linkDetailsMap.put(link.getLinkId(), link);
}
}
@Override
public void run() {
while (true) {
try {
// making a rest appi call and modifying link CurrentBWidth in
// linkDetailsMap
**for(Map.Entry<Integer, Link> entry:linkDetailsMap.entrySet())
Link link = entry.getValue();
link.setCurrentBWidth(//some vallue);
}**
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
......... ///extra code
}
最佳答案
使用ReentrantReadWriteLock使用写锁保护修改,使用读锁保护读取。您可以同时拥有许多读者,但只能有一名作者。这样,当写入者持有锁时,读取者将被阻塞。
关于java - 在修改java中的条目集值时同步对静态 HashMap 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20565587/