Thread safe way to copy a map

2019-09-06 19:00发布

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

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.

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?

标签: java guava
2条回答
干净又极端
2楼-- · 2019-09-06 19:17

From TreeMap javadoc:

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
查看更多
手持菜刀,她持情操
3楼-- · 2019-09-06 19:24

It depends on what you want:

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.

Then use ConcurrentSkipListMap

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

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

查看更多
登录 后发表回答