A small copy of the Java Collection-essential for beginners of Java and essential for beginners of java

Source: Internet
Author: User

A small copy of the Java Collection-essential for beginners of Java and essential for beginners of java

The features, implementation methods, and performance of all sets and concurrent sets are retained in the shortest length. It is suitable for those who are not so confident in reading "proficient in Java.

List

ArrayList

In array format. Space is saved, but the array capacity is limited. When the limit is exceeded, the System. arraycopy () is used to copy to the new array. Therefore, it is best to estimate the size of the array. By default, an array with a size of 10 is created when an element is inserted for the first time.

Accessing element-get (I)/set (I, e) by array subscript has high performance, which is the basic advantage of array.

Adding the element-add (e) directly at the end of the array has high performance. However, if you insert or delete the element-add (I, e), remove (I) by subscript ), remove (e), use System. when arraycopy () is used to move some affected elements, the performance degrades, which is a basic disadvantage.

Shortlist

It is implemented using a two-way linked list. The linked list has no capacity limit, but the two-way linked list itself uses more space and requires additional linked list pointer operations.

To access the element-get (I)/set (I, e) by subscript, move the pointer to the point of the tragic traversal chain table (if I> half of the array size, will be removed from the end ).

You can modify the pointer of the front and back nodes when inserting or deleting elements, but you still need to traverse some linked lists to move the pointer to the position indicated by the subscript. Only the operation-add () at both ends of the linked list can be performed (), addFirst (), removeLast (), or remove () on iterator () can save pointer movement.

CopyOnWriteArrayList

The ArrayList of concurrency optimization. With the CopyOnWrite policy, a snapshot is copied to modify the modification, and the internal pointer is directed to the new array after modification.

Because modification to the snapshot is invisible to read operations, only the write lock does not have a read lock, and the copy cost is high, this is a typical scenario that is suitable for reading more and writing less. If the update frequency is high or the array size is large, it is still Collections. synchronizedList (list). It is better to use the same lock for all operations to ensure thread security.

The addIfAbsent (e) method is added to traverse the array to check whether the element already exists. The performance is not good.

Supplement

Regardless of the implementation, returns the subscript-contains (e), indexOf (e), and remove (e) by value. All elements need to be traversed for comparison, and the performance is not as good as imagined.

There is no SortedList sorted by element values, and there is no concurrent1_list of lock-free algorithms in the thread security class. When we use the equivalence classes in the Set and Queue, some List-specific methods are missing.

Map

HashMap

The hash bucket array implemented by the Entry [] array. The array subscript can be obtained by using the hash value of the Key to obtain the size of the modulo bucket array.

When an element is inserted, if the two keys fall into the same bucket (for example, after modulo 16 for hash value 1 and 17 ), the Entry uses the next attribute to store multiple entries in a one-way linked list. The Entry in the bucket then points next to the current Entry in the bucket.

When you look for a key with a hash value of 17, first locate the first hash bucket, then traverse all the elements in the bucket with a linked list, and compare their key values one by one.

When the number of entries reaches 75% of the number of buckets (many articles say that the number of buckets used has reached 75%, but the Code does not), the bucket array will be expanded exponentially, and re-allocate all original entries, so it is best to have an estimate here.

Modulo bitwise operations (hash & (arrayLength-1) will be faster, so the size of the array is always the N power of 2, you give an initial value such as 17 will be converted to 32. By default, the initial value of the first element is 16.

Iterator () is traversed along with the hash bucket array. It looks like an out-of-order.

In JDK8, the increment value of 8 is added by default. When the Entry in a bucket exceeds the increment value, the one-way linked list is not stored as a red/black tree to speed up Key search.

LinkedHashMap

Extended HashMap adds the implementation of two-way linked list, which is called the most memory-occupied data structure. When iterator () is supported, it is sorted by Entry insertion Order (but the update is not counted. If the accessOrder attribute is set to true, all read/write accesses are counted ).

The implementation is to add the before/after pointer to the Entry, and add yourself to the front of the Header Entry during insertion. If all read/write access needs to be sorted, You Need To splice the before/after of the front and back entries to delete yourself from the linked list.

TreeMap

It is implemented by the red and black trees. For details about the length limit, see the Getting Started tutorial. Supports sorting by Key value when iterator () is enabled. You can sort keys that implement the Comparable interface in ascending order or controlled by the input Comparator. As you can imagine, the cost of inserting/deleting elements on a tree must be higher than that of HashMap.

Supports SortedMap interfaces, such as firstKey (), lastKey () to obtain the smallest key, or sub (fromKey, toKey), tailMap (fromKey) to cut a Map segment.

ConcurrentHashMap

The HashMap with concurrent optimization has 16 Write locks by default (more can be set), which effectively disperses the blocking probability and has no read locks.
The data structure is Segment [], and the Segment contains the hash bucket array. Each Segment has a lock. The Key first calculates the Segment in which it is located, and then the hash bucket in which it is located.

Supports ConcurrentMap APIs, such as putIfAbsent (key, value) replace (key, value) and CAS replace (key, oldValue, newValue ).

There is no read lock because the put/remove action is an atomic action (for example, put is a value assignment operation on the array element/Entry pointer), and the read operation does not see the intermediate status of an update action.

ConcurrentSkipListMap

The concurrent optimization SortedMap added in JDK 6 is implemented using SkipList. SkipList is a simplified alternative to the red/black tree. It is a popular sorted set algorithm. For details, see the Getting Started tutorial. The Concurrent package uses it because it supports the CAS-based lock-free algorithm, while the red/black tree does not have a good lock-free algorithm.

In particular, its size () cannot be adjusted at will and will be traversed for statistics.

Supplement

For null, HashMap and LinkedHashMap are random. When TreeMap is not set to Comparator, the key cannot be null. ConcurrentHashMap cannot be null in JDK7 (Why ?), In JDK 8, neither key nor value can be null; ConcurrentSkipListMap cannot be null for all keys and values in JDK.

Set

Almost all sets are implemented using a Map internally, because the KeySet in Map is a Set, while the value is a false value, all using the same Object. The Set feature also inherits the features implemented by the internal Map.

  • HashSet: HashMap is used internally.
  • LinkedHashSet: Implements hashmap internally.
  • TreeSet: It is the SortedSet of TreeMap.
  • ConcurrentSkipListSet: ConcurrentSkipListMap is a concurrent optimized SortedSet.
  • CopyOnWriteArraySet: The internal is the Set of CopyOnWriteArrayList concurrency optimization, using its addIfAbsent () method to implement element deduplication, as described above, the performance of this method is very general.

Supplement: It seems that a ConcurrentHashSet is missing, and there should be a simple internal implementation of ConcurrentHashMap, but JDK does not provide it. Jetty closed one by itself, and Guava directly implemented it using java. util. Collections. newSetFromMap (new ConcurrentHashMap.

Queue

Queue is a List at both ends, so it can also be implemented using arrays or linked lists.

-Common queue-

Shortlist

Yes, the sort List implemented by a two-way linked List is both List and Queue. It is the only Queue that can be put into null.

ArrayDeque

Two-way Queue implemented in a circular array. The value is a multiple of 2. The default value is 16.

An ordinary array can only add elements at the end. To support FIFO, you need to use a loop array to quickly retrieve elements from the array header: when there are two subscript at the end of the team header: When an element pops up, the subscript of the header increases progressively. When an element is added, if it is at the end of the array space, the element is assigned to the array [0] cyclically (if the subscript of the header is greater than 0 at this time, indicates that an element has been popped up in the team header, and there is space available). At the same time, the subscript at the team end points to 0, and the next element is inserted, the value is assigned to the array [1], and the subscript at the team end points to 1. If the subscript at the end of the team catches up with the team header, it means that all the space in the array is used up, and the array is resized twice.

PriorityQueue

The priority queue implemented by the binary heap is displayed. For details, refer to the Getting Started tutorial. Instead of FIFO, the queue is displayed based on the Comparable interface implemented by the element or the comparison result of the input Comparator. The smaller the value, the higher the priority, get out of the queue first. However, note that the returned results of its iterator () are not sorted.

-Thread-safe queue-

Concurrentincluqueue/concurrentincludeque

The unbounded concurrency-optimized Queue is implemented based on the linked list based on the CAS lockless algorithm.

The concurrent1_queue structure is a one-way linked list and head/tail pointers, because the next pointer of the element at the end of the team needs to be modified when the team is in the queue, and the CAS action of modifying the element that the tail points to the new team cannot be atomic, for more information about the special algorithms, see the tutorials.

PriorityBlockingQueue

The unbounded concurrency optimization PriorityQueue is also based on the binary heap. Use a public read/write lock. Although the BlockingQueue interface is implemented, it does not have any features of blocking queues, And will automatically expand when the space is insufficient.

DelayQueue

Contains a PriorityQueue, which is also unbounded. The element needs to implement the Delayed interface, and how long is the current trigger time required for each call? If it is less than 0, it indicates the trigger.
When pull () is used, peek () is used to check the element of the team header and whether it has reached the trigger time. ScheduledThreadPoolExecutor uses a similar structure.

-Thread-safe blocking queue-

BlockingQueue's queue length is limited, which is used to ensure that the speed of the producer and consumer will not be too different, so as to avoid memory consumption. After the queue length is set, it cannot be changed. When the queue is full or the queue is empty, the effects of different functions are shown in the following table:

  An exception may be reported. Returns a Boolean value. Possible blocking wait You can set the wait time.
Join Add (e) Offer (e) Put (e) Offer (e, timeout, unit)
Team-out Remove () Poll () Take () Poll (timeout, unit)
View Element () Peek () None None

ArrayBlockingQueue

BlockingQueue with fixed concurrency optimization is implemented based on cyclic arrays. There is a public read/write lock and notFull, notEmpty two Condition Management queue is full or empty when the blocking status.

LinkedBlockingQueue/LinkedBlockingDeque

BlockingQueue with long concurrency optimization can be selected based on the implementation of the linked list, so the length can be set to Integer. MAX_VALUE. Using the features of the linked list, takeLock and putLock are separated and the blocking status when the queue is full or empty is managed by notEmpty and notFull.

Supplement

JDK 7 has a sequence transferqueue. The transfer (e) method ensures that the elements put into the Producer are removed by the Consumer and then returned. This method is better than SynchronousQueue. If you have time, you need to learn it.

Java learning and communication QQ group: 589809992 let's learn Java together!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.