如何在刷新期间锁定hashmap? [英] How to lock a hashmap during refresh?

查看:183
本文介绍了如何在刷新期间锁定hashmap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态的 HashMap ,在应用程序启动时填充,每天刷新。

I have a static HashMap that is populated on application startup, and refreshed daily.

确保在刷新期间没有其他线程可以访问映射?

How can I ensure that during refresh no other thread can access the map?

@ThreadSafe
public class MyService {

   private static final Map<String, Object> map = new HashMap<>();
   private MyDao dao;

   public void refresh(List<Object> objects) {
       map.clear();
       map.addAll(dao.findAll()); //maybe long running routine
   }

   public Object get(String key) {
       map.get(key); //ensure this waits during a refresh??
   }
}



我应该引入一个简单的 refresh()期间设置和清除的布尔锁?还是有更好的选择?或者是同步机制有办法吗?

Should I introduce a simple boolean lock that is set and cleared during refresh()? Or are there better choices? Or is the synchronized mechanism a way to go?

推荐答案

使用易变图并在填充后重新分配:

You could use a volatile map and reassign it after population:

public class MyService {

   private static volatile Map<String, Object> map = new HashMap<>();
   private MyDao dao;

   public void refresh(List<Object> objects) {
       Map<String, Object> newMap = new HashMap<>();
       newMap.addAll(dao.findAll()); //maybe long running routine
       map = newMap;
   }

   public Object get(String key) {
       map.get(key); //ensure this waits during a refresh??
   }
}

这是非阻塞的, $ c> newMap 到映射是原子并确保可见性:任何后续调用 get 将基于刷新的地图。

It is non blocking, the assignment from newMap to map is atomic and ensures visibility: any subsequent call to get will be based on the refreshed map.

性能方面这应该很好,因为volatile读取几乎和正常读取一样快。易失性写入有点慢一点,但考虑到刷新频率不应该是一个问题。如果性能问题,您应该运行适当的测试。

Performance wise this should work well because volatile reads are almost as fast as normal reads. Volatile writes are a tiny bit slower but considering the refreshing frequency it should not be an issue. If performance matters you should run appropriate tests.

注意:您必须确保没有外部代码可以访问映射引用,否则该代码可能会访问过期数据。

Note: you must make sure that no external code can get access to the map reference, otherwise that code could access stale data.

这篇关于如何在刷新期间锁定hashmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆