I have a few question related to java.util.concurrent
package:
Why in the java API there is the non-concurrent TreeMap on one side and the concurrent ConcurrentSkipListMap on one other?
Why did not they call it ConcurrentTreeMap
? Is it safe to say that a SkipListMap
includes a TreeMap
?
For example a non concurrent HashMap
has got its concurrent counterpart ConcurrentHashMap
. Why does it not happen for the TreeMap
?
TreeMap and TreeSet are not thread-safe collections, so care must be taken to ensure when used in multi-threaded programs. Both TreeMap and TreeSet are safe when read, even concurrently, by multiple threads.
TreeMap can be synchronized using the Collections. synchronizedMap() method. The synchronizedMap() method of the Collections class takes the Map that has to be synchronized as a parameter and returns a thread-safe synchronized Map. The synchronizedMap() method of java.
ConcurrentHashMap class achieves thread-safety by dividing the map into segments, the lock is required not for the entire object but for one segment, i.e one thread requires a lock of one segment. In ConcurrentHashap the read operation doesn't require any lock.
They do not throw ConcurrentModificationException.
Why there is the non-concurrent TreeMap on one side and the ConcurrentSkipListMap on one other?
I suspect this was done because making a tree structure concurrent was too difficult or suffered from locking performance problems. In terms of ordered collections, SkipLists are very simple data structures and provide similar behavior and performance to trees so the ConcurrentSkipListMap
(and Set
) might have been easier to make concurrent.
I'm actually more disappointed that there isn't a non-concurrent SkipList collection myself.
Is it safe to say that a SkipListMap included a TreeMap?
No. It is safe to say that a SkipList gives similar features in terms of an ordered collection of items that gives O(logN)
performance for lookup, insert, delete, etc.. At least it gives a probabilistic approximation of that performance.
Here's a good page about skiplists. They are extremely cool data structures. I can only hope the are taught in modern programming data structures classes.
The TreeMap
class is called that way because it is implemented using a balanced search tree. The ConcurrentSkipListMap
is called that way because it's implemented using a skip list. Why is there no concurrent version of TreeMap
? Possibly because it's hard to make a tree structure that scales to high levels of concurrency; a concurrent skip list is easier to implement correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With