CopyOnWriteArrayList implementation principle and source code analysis, copyonwritearraylist

Source: Internet
Author: User
Tags concurrentmodificationexception

CopyOnWriteArrayList implementation principle and source code analysis, copyonwritearraylist

  CopyOnWriteArrayListIs a concurrent container provided in the Java concurrent package. It isArrayList with thread security and no lock for read OperationsThe write operation is implemented by creating a new copy of the underlying array.Read/write splittingThe concurrency policy, we can also call this container as a "Write-time replicaset", and similar containers in Java concurrent packages also have CopyOnWriteSet. This article analyzes the implementation principle and source code of CopyOnWriteArrayList.

Implementation Principle

We all know that the ArrayList in the Collection framework is non-thread-safe. Although the Vector is thread-safe, its performance is poor due to the simple and crude lock synchronization mechanism. CopyOnWriteArrayList provides another concurrent processing policy (for specific concurrent scenarios, of course ).

Most of the time, our system is dealingRead-write-less. The CopyOnWriteArrayList container allows concurrent reads, and the read operations are unlocked with high performance. For write operations, such as adding an element to the container,First, copy the current container, then perform the write operation on the new copy, and then point the reference of the original container to the new container.

  Advantage and disadvantage Analysis

Understand the implementation principles of CopyOnWriteArrayList, and analyze its advantages and disadvantages and use cases.

  Advantages:

  High read performance, because no synchronization measures are required, it is more suitableRead-write-less. Java list is in the same time. If another thread modifies the list container in the middle, it will throwConcurrentModificationExceptionException. CopyOnWriteArrayList, due to its idea of "read/write splitting", traversal and modification operations are used in different list containers. Therefore, when the iterator is used for traversal, ConcurrentModificationException will not be thrown.

  Disadvantages:

The disadvantages are also obvious,First, memory usage ProblemsAfter all, the original container must be copied for each write operation. When the data volume is large, the memory pressure is high, which may cause frequent GC;Second, the real-time performance cannot be guaranteed., Vector locks read and write operations to ensure strong consistency between read and write operations. CopyOnWriteArrayList, due to its implementation policy, writes and reads are applied to different new and old containers respectively. During the write operation, the read will not be blocked, but the read will be the data of the old container.

Source code analysis

After learning about the basic principles, the Code Implementation of CopyOnWriteArrayList seems easy to understand.

Public boolean add (E e) {// ReentrantLock lock to ensure thread security final ReentrantLock = this. lock; lock. lock (); try {Object [] elements = getArray (); int len = elements. length; // copy the original container. The length is the length of the original container plus one Object [] newElements = Arrays. copyOf (elements, len + 1); // Add newElements [len] = e on the new copy; // point the original container reference to the new copy setArray (newElements ); return true;} finally {// unlock lock. unlock ();}}

The added logic is simple. First copy the original container, then perform the write operation on the new copy, and then switch the reference. Of course, this process requires locking.

Delete operation

Public E remove (int index) {// lock final ReentrantLock = this. lock; lock. lock (); try {Object [] elements = getArray (); int len = elements. length; E oldValue = get (elements, index); int numMoved = len-index-1; if (numMoved = 0) // if you want to delete the end data of the list, copy the previous len-1 data to the new copy, and then switch to reference setArray (Arrays. copyOf (elements, len-1); else {// otherwise, the elements other than the elements to be deleted are copied to the new copy, and switch to reference Object [] newElements = new Object [len-1]; System. arraycopy (elements, 0, newElements, 0, index); System. arraycopy (elements, index + 1, newElements, index, numMoved); setArray (newElements);} return oldValue;} finally {// unlock lock. unlock ();}}

Similarly, the delete operation copies all elements except the elements to be deleted to the new copy, switches the reference, and points the original container reference to the new copy. The same write operation must be locked.

Let's take a look at the read operation. The read operation of CopyOnWriteArrayList does not need to be locked, and the performance is very high.

public E get(int index) {        return get(getArray(), index);    }

Read directly without locking

 private E get(Object[] a, int index) {        return (E) a[index];    }
Summary

This article analyzes the implementation principle and source code of CopyOnWriteArrayList, and analyzes the advantages and disadvantages of CopyOnWriteArrayList (CopyOnWriteSet is also provided in Java concurrent packages, and the principle is similar ). In fact, the advantages and disadvantages of the so-called concurrent containers depend on whether we can make reasonable choices and applications in the face of specific concurrent scenarios. I also hope this article will help you with the children's shoes you need.

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.