How to synchronize a card between one r / w Thread and one read-only thread?

I have a synchronized Card (through Collections.synchronizedMap()) that is read and updated by thread A. Thread B accesses the Card only through Map.keySet()(read-only).

How do I sync this? docs say keySet () (for Collections.synchronizedMap) "No need to be in a synchronized block." I can put Thread A read / write access into a synchronized block, but is this even necessary?

It seems strange to me that I even use a synchronized map or a synchronized block if Map.keySet does not need to be synchronized (according to the docs link above) ...

Update: I missed that the keySet iteration should be synchronized, although getting the keySet does not require synchronization. It is not particularly interesting to have a keySet without being able to view it, so the end result = synchronization is required. Use ConcurrentHashMap instead.

+5
source share
3 answers

To make a genuine lock Mapfor read / write and read / single close, you can take a look at the shell Collectionsfor synchronizedMap()and replace all statements synchronizedwith ReentrantReadWriteLock. This is a good job. Instead, you should switch to a use ConcurrentHashMapthat does all the right things.

keySet() synchronized, synchronized Collections.synchronizedMap(). Javadocs , , , , , keySet(), SynchronizedSet, .

, , , , - , . , , , . Map , , - .

+2

, , , :

Map m = Collections.synchronizedMap(new HashMap());
      ...
Set s = m.keySet();  // Needn't be in synchronized block
      ...
synchronized(m) {  // Synchronizing on m, not s!
    Iterator i = s.iterator(); // Must be in synchronized block
    while (i.hasNext())
        foo(i.next());
}

, . , , keySet() , Map. , .

, , , , Map, Collections.synchronizedMap. Map s.

+2

. , Collections.synchronizedMap(), , Map. , set impl, keySet(), , , .

, Thread B - , Thread A.

You might want to explore ConcurrentHashMap. It provides useful semantics for this use case. Iterating over a collection view in CHM ( likekeySet() ) gives useful parallel behavior ("loosely matched" iterators). You will go through all the keys from the collection state at the iteration, and you will see or not see the changes after creating the iterator.

+2
source

All Articles