Alex Florescu
Alex Florescu

Reputation: 5151

Collections.synchronizedSortedMap vs ConcurrentSkipListMap for a sorted map to be used with concurrency

I need to use a sorted map that will be accessed concurrently (an iterator may be reading through the map while another thread will add new entries).

I have so far found two ways of doing it, either by using Collections.synchronizedSortedMap(new TreeMap()) or using a ConcurrentSkipListMap.

What are the advantages and disadvantages of one approach over the other? ConcurrentSkipListMap seems easier to use, but what other factors should I be considering?

Upvotes: 1

Views: 1406

Answers (1)

assylias
assylias

Reputation: 328649

Generally speaking, the concurrent collections offer better scalability than the synchronized collections, but synchronized collections allow you to lock the whole collection whereas concurrent collections don't.

Whether you need one or the other depends on your use case.

an iterator may be reading through the map while another thread will add new entries

Then you probably don't want to use Collections.synchronizedSortedMap(new TreeMap()) because it requires locking the whole map while iterating.

ConcurrentSkipListMap on the other hand provides weakly-consistent iterators (i.e. iterators that take a snapshot of the map before starting the iteration, allowing you to modify the map during the iteration without side effects).

Upvotes: 4

Related Questions