Interviewer: You're not a qualified engineer in Java, thread-safe collection you are vague?


 If your concept related to the set before a certain understanding, that reading of this blog will make you have a broader set of knowledge, if you are a little fuzzy on the concept of a collection, you can take the initiative to point to open the link below We hope to help it to you!

A collection of related knowledge Review

The following summary of basic knowledge about the link has a detailed blog at the beginning of the text, can point to open for more reading.

  • ArrayList
    array structure to achieve, fast queries, additions and deletions slow
    JDK1.2 version. Fast operating efficiency,Thread safe

  • LinkedList
    list implementation, slow queries, additions and deletions fast

  • Vector
    array structure to achieve, fast queries, additions and deletions slow
    JDK1.0 version. Slow operating efficiency,Thread Safety

  • HashSet
     This class implements the Set interface, backed by a hash table (actually HashMapinstance). Iterative sequence set does not make any guarantee; in particular, it can not guarantee the order remained unchanged for some time. This class allows null elements. ( HashSetBased on the HashCodeimplemented elements not duplicate)

  • SortedSort
     the Set further provides a total ordering its elements. Elements using their natural order, or generally create an orderly Setprovided when Comparatorsorting. Set to change the iterator will traverse ascending order of elements in the collection. It provides several additional operations to take advantage of ordering. (This interface is the set of analogues SortedMap).

  • LinkedHashSet
     hash table and linked list implementation of the Setinterface, with predictable iteration order. This implementation is different HashSet, it maintains a doubly linked list running for all entries. That LinkedHashSetmay be reserved for our insertion order.

  • TreeSet
     implement liter descending order, if need to use TreeSet sort must be allowed to compare objects that implement Comparablethe interface, and override the compareTo()method, the method defined sort criteria (according to what sort), sort (ascending or descending).

  • HashMap
     based implementation hash table of Mapthe interface. This implementation provides all of the optional map operations, and allows nullthe value of nullthe key. (Except that it is not synchronized, and allow null outside the HashMapclass roughly equivalent Hashtable). This class can not be guaranteed sequence mapping; in particular, it does not guarantee that the order constancy.
     JDK1.2 version,Thread safe, Fast operating efficiency; allowed nullas Keyor value.

  • Hashtable
     class implements a hash table, it maps keys to values. Any non- nulltarget or can be used as key values.
    In order to successfully store and retrieve objects from the hash table, the key must be used to achieve the object hashCodemethods and equalsmethods.
     JDK1.0 version,Thread SafetyOperating efficiency slow; not allowed to use nullas Keyeither value.

  • TreeMap
     The method may speak Map key-value pairs in accordance with the natural ordering of the key-value;

FIG frame set (Map omitted)

Here Insert Picture Description

Collection of utility methods

 In the previous article we mentioned a few simple ways Collection of tools:

method description
public static void reverse(List<?> list) Reversing the order of the elements in a set of
public static void shuffle(List<?> list) Reset random sequence set elements
public static void sort(List<?> list) Ascending order (element must implement Comparable interface)

 Of course, it also provides multiple methods available thread-safe collection:

method description
static <T> Collection<T> synchronizedCollection(Collection<T> c) Returns a collection by the specified collection supports synchronized (thread-safe).
static <T> List<T> synchronizedList(List<T> list) Returned by the specified list of supported list synchronization (thread-safe).
static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) Returned by the specified map mapping support synchronized (thread-safe).
static <T> Set<T> synchronizedSet(Set<T> s) Returned by the specified collection to support synchronized (thread-safe) set.
static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) Returned by the specified sorted map backed synchronized (thread-safe) sorted map.
static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) Returns a synchronized (thread-safe) sorted set by the specified sorted set supports.

synchronizedList(List list) 为例

Source code analysis

Here Insert Picture Description

①: After the point in, we will listpass in, and then a three-judge unary operator according to the type of the random access, the determination result is newa new object to new SynchronizedList<>(list))an example;
②: SynchronizedList<>(list))a method in the user-entered configuration to listgive the parent class, and to listpay its own attribute final List<E> list;
③: SynchronizedList<>(list))parent came to pass listwithout empty conditions, to keep it final Collection<E> c, and will get inside a class object mutexis equivalent to a lock object;
④: when using the method set of operations, here to add, for example, by using an internal class object method within the class add, the method must get access to the tag, the party calls further using conventional addmethods (⑤);
 overall, through a simple set of original packaging, that is, the addition of a lock object mutexto guarantee the security thread; ( mutexis an instance variable, each set is only one of the instance variables)

Security guarantee thread

 When a plurality of such method needs to be performed on the set of operations, it is necessary to get the lock flag set can operate, concurrently executing threads may be unsafe original set, a set of thread-safe to upgrade serial implementation;
Here Insert Picture Description

Acting ideas

Here Insert Picture Description
 As a class we use, we can not meet the current needs of the time, no need to operate the original class, but a class together, enhance its function, which is proxythe agent; including the now popular Springcore framework on two: factory + agency;

summary

  • JDK1.2 offer, unified interface, high maintenance, but because both use synchronizedLista mutex to achieve, so there is no performance improvement; therefore Essentially, the method and the use of Vector and HashTable are not very different;

CopyOnWriteArrayList class

Learn to read and write locks

Learn to read and write lock is essentially a knowledge of the class design pattern, because the type of design patterns and read-write locks are different there are similarities together understanding will be more impressive; providing links on a read-write lock before the relevant :

 For read and write operations, the write locks are mutually exclusive, rather than concurrently, rather than mutually exclusive read lock can execute concurrently, so a mutex it, do not write it does not exist, because mutually exclusive, so are not concurrent, compared to this, the read-write locks can greatly improve efficiency.

Source code analysis

First contact with a new class, we should not try to get to know his definition, you need to understand what it is essentially done by reading the source code, then you will know the meaning and origin of its name, this is the most important;

  • Write operation (in addexample)
    Here Insert Picture Description
     For a write operation, where a comparison with a clever way, i.e., the current class instance variables get arraypaid to a new array object elements, and then modified based on the particular array, i.e. elmentsthe values assigned to newElements, and newElementscapacity plus one, and then passed in e(i.e., where the character "a") into the memory newElements, and all is ready, and then replaced by a new array directly out of the class instance variables array; &
    ESMP; in general, during the addition process data, i.e., write, and no class instance variables arrayfor any operation, but only to create a new object array, then an array of the new target after the operation is complete arrayreplacement;
     when a plurality of writes when the array is operated, because there are reasons for re-entry lock, can only be executed serially, it does not support concurrent ensure the security thread;
  • Reading Methods
   public E get(int index) {
        return get(getArray(), index);
    }

 Obviously not write lock object, but stored directly support the concurrent execution;

CopyOnWriteArrayList exclusive right to read and write?

 Obviously not mutually exclusive, thanks to a write operation in the clever design: the time during the write operation that is not a class instance variables ah arrayoperate, but write in the new array, when the write is complete after a direct replacement; obviously when multiple concurrent read and write operations performed when the process of reading the writing process does not see the digital operation of the operation, so thread-safe, read and write are not mutually exclusive!
 Here analogy can update App, such as QQ carrying out an updated version of the time, affect the user do? Obviously not, then the program will ape the new version of the test is completed, the new version of the code will replace the old version, obviously the user when in use, use the function will not be affected, so the analogy here to read and write is not mutually exclusive ;
 therefore, the implementation class is not only thread-safe, but under more of a read operation situation, the program will double the efficiency! ! !

how to use?

 Use and ArrayList is exactly the same, which also embodies a design pattern: interface reference point to achieve the object class, easier to replace realize, is a good way to decouple
Here Insert Picture Description

vector与CopyOnWriteArrayList

 If the program development process, we need a thread-safe List, try not to use is not recommended Vectorin earlier versions of JDK which we will use Vector, but because of relatively low efficiency ( Vectorall methods are added to the re-entry lock, mutual exclusion, do not support concurrent), thus providing an efficient thread-safe CopyOnWriteArrayListafter collection classes ( CopyOnWriteArrayListread and write, read support concurrent), has been gradually phased out of Vectoruse;

summary

  • Thread-safe ArrayList, enhanced version of the separate read and write (read and write not mutually exclusive);
  • Write lock, read no lock, no obstruction between the reader, better than the read-write locks;
  • When writing copy to copy a container, adding a new element, and finally replace references.
  • ArrayList tantamount to use;

CopyOnWriteArraySet class

CopyOnWriteArraySet underlying implementation is CopyOnWriteArrayList, but List feature is ordered by an index, the elements can not be repeated, the key point: how to re-implement it?

private final CopyOnWriteArrayList<E> al;  //底层实现 ArrayList

public CopyOnWriteArraySet() {
        al = new CopyOnWriteArrayList<E>();
    }

Source code analysis

  • In a addmethod, for example, to re-look at the principle of Set
    /**
     * Appends the element, if not present.
     *
     * @param e element to be added to this list, if absent
     * @return {@code true} if the element was added
     */
    public boolean addIfAbsent(E e) {
        Object[] snapshot = getArray();
        return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
            addIfAbsent(e, snapshot);
    }

    /**
     * A version of addIfAbsent using the strong hint that given
     * recent snapshot does not contain e.
     */
    private boolean addIfAbsent(E e, Object[] snapshot) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] current = getArray();
            int len = current.length;
            if (snapshot != current) {
                // Optimize for lost race to another addXXX operation
                int common = Math.min(snapshot.length, len);
                for (int i = 0; i < common; i++)
                    if (current[i] != snapshot[i] && eq(e, current[i]))
                        return false;
                if (indexOf(e, current, common, len) >= 0)
                        return false;
            }
            Object[] newElements = Arrays.copyOf(current, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

 The key code is as follows, and the rest of CopyOnWriteArrayListsimilar
Here Insert Picture Description


For collections thread-safe, there are many, but on the blog post will make readers feel more boring to read, and this blog, I spend a lot more time and energy and hope to receive your thumbs or concerns. thanksgiving! thank! grateful! The other set of thread-safe to be updated ...

Published 87 original articles · won praise 243 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_44717317/article/details/104972073