Introduce the understanding of the Java container

1 Introduce the understanding of the Java container?

1ArrayList

Default capacity size : private static final int DEFAULT_CAPACITY = 10; Note: If no element is added to the collection, the capacity is 0, and after adding an element, the capacity is 10; when the array length is 10, the capacity will be expanded to 1.5 each time . Times

ArrayList is not safe under concurrent conditions. CopyOnWriteArrayList : Copy on write to solve this problem. CopyOnWriteArrayList uses Lock locks , which is more efficient. The core idea is that if there are multiple callers (Callers) requiring the same at the same time Resources (such as memory or data storage on disk), they will jointly obtain the same pointer to the same resource, until a caller tries to modify the content of the resource, the system will truly make a private copy (private copy) To the caller, the original resources seen by other callers remain unchanged. This process is transparent to other callers. The main advantage of this approach is that if the caller does not modify the resource, no private copy will be created, so multiple callers can share the same resource when just reading . There is no need to lock when reading. If multiple threads are adding data to the CopyOnWriteArrayList when reading, the old data will still be read, because the old CopyOnWriteArrayList will not be locked when writing. The design idea of ​​CopyOnWriteArrayList 1 read and write separation, read and write separation 2 final consistency 3 use the idea of ​​opening up space to solve concurrency conflicts , the disadvantage is also the way to open up space: it needs to take up a certain amount of memory space;

ArrayList: must open up a continuous space, fast query, slow addition and deletion;
LinkedList: no need to open a continuous space, slow addition and deletion, fast query;
Insert picture description here

2LinkedList

LinkedList: No need to open up a continuous space, slow additions and deletions, fast query;

3Vector

Array structure realization, fast query, slow addition and deletion; slow operation efficiency, synchronized , thread safety.

4Set

Unordered, no subscript, and elements cannot be repeated;
HashSet: The bottom layer is a HashMap. Note: HashSet storage process:
Step 1: Calculate the saved location according to the hashCode . If the location is empty, save it directly, otherwise perform the second step.
Step 2: Execute the equals method. If the method returns true, it is considered a duplicate and refuses to store, otherwise a linked list is formed.
TreeSet (red-black tree): Based on the sort order to achieve non-repetition. The SortedSet interface is implemented, and the collection elements are automatically sorted. The type of element object must implement the Comparable interface and specify the sorting rules. Determine whether it is a repeating element through the CompareTo method.

Set and List have the same principle: In the case of multi-threading, the ordinary Set collection is thread-unsafe ; there
are two solutions: 1 Use the Set class of the synchronized package of the Collections tool class 2 Use CopyOnWriteArraySet

5Map

Used to store arbitrary key-value pairs (Key-Value) . Key: disorder, no subscript, no repetition (unique) . Value: unordered, no subscript, repeat allowed. The thread is not safe and the operation efficiency is fast; it is allowed to use null as the key or value . Storage structure: hash table (array + linked list + red-black tree);
default initialization capacity: static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 maximum array capacity: 1 << 30 ; default load factor: 0.75 f; //The expansion
linked list is adjusted to the linked list length threshold of the red-black tree (JDK1.8): static final int TREEIFY_THRESHOLD = 8 ; the red-black tree is adjusted to the linked list length threshold of the linked list (JDK1.8): static final int UNTREEIFY_THRESHOLD = 6 ; the linked list Adjusted to an array of red-black trees



Minimum threshold (JDK1.8):
static final int MIN_TREEIFY_CAPACITY = 64 ;

ConcurrentHashMap is a thread-safe and efficient HashMap implementation in Java . Usually, if you want to use the map structure with high concurrency, it is the first thing that comes to mind. Compared with hashmap, ConcurrentHashMap is a thread-safe map, which uses the idea of lock segmentation to improve concurrency. Key elements of the JDK 1.6 version : segment inherits the role of ReentrantLock as a lock, providing thread safety guarantee for each segment; segment maintains several buckets of hash table, and each bucket is a linked list composed of HashEntry. After JDK1.8 , ConcurrentHashMap abandoned the original Segment lock, and adopted CAS + synchronized to ensure concurrency security.

6Hashtable

JDK1.0 version, thread safe, slow operation efficiency ; null is not allowed as key or value . The initial capacity is 11 and the loading factor is 0.75.

7HashMap allows null to be used as key or value. Why is this happening? HashTable does not allow the key value to be null or the value to be null; then how is the null of the HashMap stored?

  public V put(K key, V value) {
    
    
        return putVal(hash(key), key, value, false, true);
    }
static final int hash(Object key) {
    
    
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

8Why ConcurrentHashMap is so good and HashMap should be used?

ConcurrentHashMap is an alternative to hashTable . ConcurrentHashMap uses Segment lock + HashEntry , while HashTable uses Syncronized locks. All threads compete for one lock. Segment segment lock inherits ReentrantLock, **When the number of concurrency is high, ReentrantLock has a lower overall overhead than Syncronized. **But there is still overhead, HashMap will not have such overhead!

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/115304878