In the shortest possible space, the features, implementations, and performance of all collections and concurrent collections are smoothed over. Suitable for all "proficient in Java", in fact, not so confident people read. "Turn from: the Love of Money"
Expect to be more than just for interview, usually choose data structure, also can consider its cost and efficiency, do not look at the API appropriate to use.
1.list1.1 ArrayList is implemented as an array. Space-saving, but the array has a capacity limit. When the limit is exceeded, 50% capacity is added and copied to the new array with System.arraycopy (). It is therefore better to give a pre-estimate of the size of the array. The default is to create an array of size 10 when you insert the element for the first time.
The ability to access elements-get (i) and set (i,e) by array subscripts is a fundamental advantage of arrays.
If you press subscript to insert an element, delete an element-add (i,e), remove (i), remove (e), you use System.arraycopy () to copy the affected elements of the moving part, and the performance becomes worse.
The more elements that are in front of you, the more element you want to move when modifying. Adding elements directly to the end of the array-the usual add (e)-Removes the last element without affecting it.
1.2 LinkedList
Implemented in a doubly linked list. There is no capacity limit on the list, but the doubly linked list itself uses more space, and each insertion of an element constructs an additional node object, which also requires an additional list pointer operation.
Press the subscript access element-get (i), set (I,e) to the tragic part of the traversed list moves the pointer in place (if half of the size of the i> array is moved from the end).
When inserting, deleting elements, you can modify the pointers to the front and back nodes without copying the move. However, it is still necessary to partially traverse the pointer of the linked list to move to the position indicated by the subscript.
Only the Operation-add (), AddFirst (), Removelast (), or remove () on the iterator () at the ends of the list can dispense with the pointer movement.
Apache Commons has a treenodelist, inside is a binary tree, you can quickly move the pointer in place.
1.3 Copyonwritearraylist concurrency-optimized ArrayList. Based on the immutable object policy, a copy of the array snapshot is modified, modified, and the internal pointer points to the new array.
Because the modification of the snapshot is not visible to the read operation, there is no mutual exclusion between read and write, and there is no mutual exclusion between reading and writing, only write-write to lock mutually exclusive. But copying snapshots is expensive, typically for scenarios where read and write less.
Although the Addifabsent (e) method is added, the array is traversed to check if the element already exists, and performance is not as good as expected.
1.4 Sorry no matter what the implementation, return the subscript contains (e), IndexOf (e), remove (e) to traverse all elements for comparison, performance can not be imagined too good. There are no sortedlist sorted by element value. In addition to Copyonwritearraylist, there is no other thread-safe and concurrency-optimized implementation such as Concurrentlinkedlist. There is a lack of a list-specific method such as get (i) when using equivalent classes in Set and queue. If the update frequency is high, or the array is large, it is necessary to use the Collections.synchronizedlist (list), the same lock for all operations to ensure thread safety.
2.map2.1 HashMap
An array of hash buckets implemented in entry[] array, with the hash value of key to take the size of the bucket array to get the array subscript.
When inserting an element, if two keys fall in the same bucket (for example, hash values 1 and 17 modulo 16 are the first hash), we call this a hash conflict.
The JDK practice is the list method, entry with a next property to implement multiple entry in a one-way linked list storage. When looking for a key with a hash value of 17, locate the hash bucket, and then the list iterates through all the elements in the bucket, comparing its hash value to the key value.
In JDK8, a new default of 8 is added to the valve value, when a bucket of entry more than valve value, do not use a one-way list and red-black tree to store to speed up key search speed.
Of course, it is best to have only one element in the bucket, not to compare. So by default when the number of entry reaches 75% of the number of buckets, the hash collision is more severe, multiplying the bucket array and reallocating all the original entry. The cost of expansion is not low, so it is better to have a pre-estimate.
Modulo and operation (hash & (ARRAYLENGTH-1)) will be faster, so the size of the array is always 2 of the N-square, you give an initial value, such as 17 will be converted to 32. The default initial value when the element is first placed is 16.
Iterator () is traversed by a hash-bucket array, which appears to be a disorderly order.
2.2 Linkedhashmap
Extending the HashMap, each entry adds a doubly linked list, claiming to be the most memory-occupying data structure.
Support for iterator () is sorted by entry in the insertion order (if the Accessorder property is set to True, all read and write access is sorted).
When inserting, entry adds himself to the front of the header entry. If all read and write access to order, but also to the front and back entry before/after splicing to delete themselves in the list, so this time the read operation is also thread insecure.
2.3 TreeMap
With red and black trees, the red and black trees are called self-balancing binary trees:
对于任一节点而言,其到叶节点的每一条路径都包含相同数目的黑结点。
The above rules, so that the number of layers of the tree will not be too far, so that all operations of the complexity of not more than O (LGN), but also make the insertion, modification to the complex left-right rotation to maintain the balance of the tree.
Support for iterator () is sorted by key value and can be sorted in ascending order of key that implements the comparable interface, or controlled by an incoming comparator. Conceivably, the cost of inserting/deleting elements in a tree must be greater than the hashmap.
Supports the SortedMap interface, such as Firstkey (), Lastkey () to obtain the largest minimum key, or sub (Fromkey, Tokey), Tailmap (Fromkey) to cut a section of the map.
2.4 Enummap
The principle of enummap is that in the constructor to pass in the enumeration class, it constructs a large array with all the values of the enumeration, by enum. The ordinal () subscript to access the array. Good performance and memory footprint.
In the ointment, because to implement the map interface, and V get (object key) in the key is an object instead of the generic k, so security, enummap each access to the key first type judgment, in the JMC recorded a low sampling hit frequency.
2.5 Concurrenthashmap
concurrency-optimized hashmap.
The classic design in JDK7, the default 16 write lock (can be set more), effectively spread the probability of blocking. The data structure is segment[], each segment a lock. Inside the segment is the hash bucket array. Key first calculates which segment it is in, and then calculates which hash bucket it is in.
There is no read lock because the Put/remove action is an atomic action (for example, the entire process of a put is an assignment of an array element/entry pointer), and the read operation does not see an intermediate state of an update action.
But in the JDK8, Segment['s design was abandoned, instead carefully designed to lock only when needed.
Supports the Concurrentmap interface, such as Putifabsent (Key,value) with the reverse replace (key,value) and the Replace (key, OldValue, NewValue) that implements CAs.
2.6 Concurrentskiplistmap
JDK6 new concurrency-optimized sortedmap, implemented in Skiplist architecture. The concurrent package chooses it because it supports a CAS-based lock-free algorithm, while the red-black tree does not have a good lock-free algorithm.
In principle, you can imagine the N-storey of multiple linked lists, where the elements are sparse to dense, and each element has pointers to the right and down. Starting from the first floor, if the value on the right side is larger than expected, go down one level and go ahead.
Typical space-changing time. Each time you insert, you have to decide which layers to insert, and decide if you want to build more than one floor.
Its size () also cannot be arbitrarily adjusted, will be all over the historical statistics.
3.Set
All sets are almost internally implemented with a map, because the keyset in the map is a set, and value is a false value, all using the same object.
The features of set also inherit the characteristics of the internal map implementations.
HashSet: The interior is hashmap.
linkedhashset: The interior is linkedhashmap.
TreeSet: Inside is the sortedset of TreeMap.
Concurrentskiplistset: Internal is the concurrency-optimized sortedset of Concurrentskiplistmap.
Copyonwritearrayset: The internal is Copyonwritearraylist's concurrency optimized set, using its addifabsent () method to implement element de-weight, as described earlier, the performance of the method is very general.
It seems that there is a concurrenthashset, there should be an internal use of concurrenthashmap simple implementation, but the JDK is not provided. Jetty himself simply sealed one, guava directly with the Java.util.Collections.newSetFromMap (New Concurrenthashmap ()) implementation.
4.Queue
A queue is a list that is in and out of both ends, so it can also be implemented using arrays or linked lists.
4.1 Normal queue
4.1.1 LinkedList
Yes, the LinkedList implemented in a doubly linked list is both a list and a queue.
4.1.2 Arraydeque
A two-way queue implemented in an array of loops. The size is a multiple of 2, and the default is 16.
In order to support FIFO, that is, the element is pressed from the end of the array (fast), the element is removed from the array head (ultra-slow), it can no longer use the implementation of ordinary ArrayList, instead of using the loop array.
There are two subscripts at the end of the team head: When the element is ejected, the team head subscript increments, and when the element is added, the tail subscript increments. If the element is added to the end of the array space, the element is assigned to the array [0], the end of the queue points to 0, and then the next element is assigned to the array [1], and the tail subscript points to 1. If the bottom of the line is chasing the team head, it means that all the space in the array has been exhausted, doubling the array.
4.1.3 Priorityqueue
The priority queue implemented with the balanced binary minimum heap is no longer FIFO, but the result of the comparable interface or incoming comparator by the element, the smaller the value, the higher the priority, the more first the team. However, note that the return of its iterator () is not sorted.
Balance the minimum binary heap, with a simple array to express, can be quickly addressed, no pointers or anything. The smallest of the two children in queue[0], such as queue[4], will be in queue[2*4+1] and queue[2* (4+1)], i.e. queue[9] and queue[10].
When you queue, insert queue[size], and then double-align the heap to the top.
Out of the team, pop queue[0], and then take the queque[size] out of the two forks to compare the adjustment heap.
The initial size is 11 and auto 50% expands when space is not enough.
4.2 Thread-Safe queues
4.2.1 Concurrentlinkedqueue/deque
Unbounded concurrency-optimized queue, based on the linked list, implements a non-locking algorithm that relies on CAs.
The structure of Concurrentlinkedqueue is one-way linked list and head/tail two pointers, because the queue needs to modify the tail element of the next pointer, as well as modify the tail point to the newly enqueued element two CAs action cannot atoms, so the need for a special algorithm.
4.2.2 Priorityblockingqueue
Unbounded Priorityqueue is also a two-fork heap based on array storage. A common lock for thread safety. Although the implementation of the Blockingqueue interface, but because of the unbounded, in fact, there is no blocking the characteristics of the queue, the space is not enough when the automatic expansion.
4.2.3 Delayqueue
The interior contains a priorityqueue, which is equally unbounded. A common lock for thread safety. The element needs to implement the delayed interface, which is required to return the current off-trigger time for each invocation, and less than 0 to indicate the trigger.
Pull () looks at the elements of the team header with Peek () and checks to see if the trigger time is reached. The scheduledthreadpoolexecutor uses a similar structure.
4.3 Thread-Safe blocking queues
The Blockingqueue queue length is limited to ensure that producers and consumers are not too far apart to avoid running out of memory. Cannot be changed after the queue length is set. When the queue is full, or the queue is empty when it is queued, the effects of different functions are shown in the following table:
|
Report the anomaly immediately. |
Return to Boolean immediately |
Blocking wait |
can set the waiting time |
| Team |
Add (E) |
Offer (e) |
Put (e) |
Offer (E, timeout, unit) |
| Out Team |
Remove () |
Poll () |
Take () |
Poll (timeout, unit) |
| View |
Element () |
Peek () |
No |
No |
4.3.1 arrayblockingqueue
The blockingqueue of the fixed-length concurrency optimization is also based on the loop array implementation. There is a public lock with Notfull, notempty two condition to manage the blocking state when the queue is full or empty.
4.3.2 Linkedblockingqueue/deque
Can select long concurrency optimized blockingqueue, based on the linked list implementation, so you can set the length of integer.max_value to become unbounded without waiting.
Using the characteristics of the list, the Takelock and putlock two locks are separated, and the blocking state of the queue full or empty is continued with notempty and Notfull.
4.4 Synchronization Queue
The Synchronousqueue synchronization queue itself has no capacity, and when placed into an element, such as waiting for an element to be taken away by another thread's consumer and returned. JDK Line constructor with it.
JDK7 also has a linkedtransferqueue, on the basis of common thread-safe blockingqueue, add a transfer (e) function, the same effect as synchronousqueue.
5. Reference documentation
-
Red and Black tree : https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/03.01.md
-
Skip Table : http://blog.sina.com.cn/s/blog_72995dcc01017w1t.html
-
two fork pile:http://blog.csdn.net/lcore/article/details/9100073
-
concurrentlinkedqueue: http://www.ibm.com/developerworks/cn/java/j-jtp04186/
Small copy of Java collection