客户端读取HashMap时如何刷新它 [英] How to refresh HashMap while clients read from it

查看:69
本文介绍了客户端读取HashMap时如何刷新它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态的 HashMap ,该静态代码在服务器启动时初始化.客户端在登录时从此地图初始化其数据.
现在,我需要刷新此地图,但是客户端可以同时登录并从该地图获取数据.

I have a static HashMap that is initialized on server startup. Clients initialize their data from this map when they login.
Now I need to refresh this map, but clients can login and get data from this map at the same time.

我可以在阅读时更改如下所示的地图参考吗?我不能使用 synchronized ,因为它们可以同时读入并且只有一个线程在写.

Can I change reference of map like below while they read? I cant use synchronized because they can read in at the same time and only one thread is writing.

   public void refresh() {
       Map<String, Object> newMap = prepareData();
       map = newMap;
   }

推荐答案

让我们假设刷新"意味着您要用从(例如)文件中加载的新集替换哈希图中的所有条目.

Lets assume that "refresh" means that you want to replace all entries in the hashmap with a fresh set loaded from (say) a file.

如果新映射中的键集是原始映射中的键的超集,并且您的应用程序不在乎客户端是否可以同时设置旧映射的一部分和新映射的一部分,那么您可以使用 ConcurrentHashMap 而不是 HashMap ,然后将这些条目替换为一系列 put 调用.

If the set of keys in the new mapping is a superset of the keys in the original mapping, AND if you application doesn't care if clients can set part of the old mapping and part of the new mapping at the same time, then you could use a ConcurrentHashMap instead of a HashMap, and replace the entries with a sequence of put calls.

但是,如果键不同(或可能不同),或者从客户端的角度出发,更新必须是原子的,则 ConcurrentHashMap 无效.相反,您需要将 map 声明为 volatile ,并根据您的问题实施 refresh()方法.

However, if keys are (or could be) different, or if the update needs to be atomic from the client's perspective then a ConcurrentHashMap is not going to work. Instead, you need to declare map as a volatile and implement your refresh() method as per your question.

正如您所指出的那样,使用 synchronized (或单写多读锁定)可能会导致并发瓶颈.

As you point out, using synchronized (or a single-writer-multiple-reader lock) is liable to lead to a concurrency bottleneck.

注意:使用 volatile 可能比使用 ConcurrentHashMap 更好的性能,即使在后者是可行的解决方案的情况下.

Note: using a volatile is likely to give better performance than using a ConcurrentHashMap even in the cases where the latter is a viable solution.

这篇关于客户端读取HashMap时如何刷新它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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