What operations depend on the capacity of a Linked

2019-07-17 20:38发布

问题:

I am using a ConcurrentHashMap as my datastructure because mutiple threads will be reading and writing to it concurrently. But I am finding that the client code will also need to iterate over it quite often . So I took a look in LinkedHashMap class which gives better iteration performance and found this section in its java doc :

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

So iteration doesn't depend on capacity .What other operations depend on initial capacity for a LinkedHashMap or HashMap in general ?Also is there any concurrent version of the LinkedHashMap in recent JDK versions ?

回答1:

Except for iteration what other operations depend on initial capacity for a LinkedHashMap

As it states, the capacity isn't important for iteration. The initial capacity rarely makes much difference and if your load factor is sensible, the capacity will grow as required.

Also is there any concurrent version of the LinkedHashMap in recent JDK versions

ConcurrentHashMap is the closest. If you need concurrent access use this one.



回答2:

If you look at the HashMap javadoc it states that:

The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.

also that

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

The LinkedHashMap is an implementation based in HashTable and using linked list to maintain order. The initial capacity won't affect the iteration performance. I believe that the only operation that will depend on the capacity is the insertion operations that may cause a table rehashing. Map