线程安全的方式来复制地图 [英] Thread safe way to copy a map

查看:99
本文介绍了线程安全的方式来复制地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JDK 7,SQLite,并且在我的项目中使用了番石榴.

Am using JDK 7, SQLite, and have Guava in my project.

我有一个少于100个条目的TreeMap,它由一个工作者"线程每秒更新数百次.我现在正在编写一个组件(另一个线程-"DB线程"),该组件每5或10秒将映射写入我的数据库.

I have a TreeMap with less than 100 entries that is being updated by a single "worker" thread hundreds of times a second. I am now writing a component (another thread - the "DB thread") that will write the map to my database every 5 or 10 seconds.

我知道我需要制作地图的深层副本,以便DB线程将使用快照,而worker线程将继续其工作.我正在查看

I know that I need to make a deep copy of the map so the DB thread will use a snapshot, while the worker thread continues its job. I am looking at the Guava Maps class which has many methods that make copies, but I am not sure if any of them meet my needs to synchronize on the map whenever a copy is needed. Is there a method there that will meet my needs, or should I write a synchronized block to make my own deep copy?

推荐答案

这取决于您的需求:

如果您想要一个完全并发的映射(添加时不能读取等等),您应该使用JSlain在我面前说的话.

If you want a fully concurrent map (cant read while adding and so on) You should use what JSlain said before me.

如果您想要的只是该地图的当前快照,并且您不关心地图是否会被修改,只要您使用的迭代器不会被更改即可.

If all you want is the CURRENT snapshot of the map and you do not care if the map will be modified as long as the iterator you are using wont be changed.

然后使用 ConcurrentSkipListMap

这将为每次迭代提供一个新的独立迭代器,因此即使更改了真实地图,您也不会注意到它.

This will provide each iteration with a new independent iterator so even if the real map is changed you wont notice it.

您将在下一次更新中看到它(在您的情况下为5秒.)

You will see it in the next update (5 seconds in your case.)

这篇关于线程安全的方式来复制地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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