ArrayList source code and multithreading Security Problem analysis

Source: Internet
Author: User

1.ArrayList source code and multithreading Security Problem analysis

Before analyzing ArrayList thread safety, we analyzed this type of source code to find out where a thread-safety problem might occur, and then verify and analyze it.

1.1 Data structures

ArrayList is used to save elements inside an array, the data is defined as follows:

transient Object[] elementData; // non-private to simplify nested class access

This array is a shared resource in ArrayList, and it is possible to have thread safety issues if you do not synchronize control when multithreading is operating on this data.

Analysis of problems that may occur with the 1.2 Add method

First, let's look at the source code of add as follows:

public boolean add(E e) {    ensureCapacityInternal(size + 1);    elementData[size++] = e;    return true;}

There are two operations in this method, one is the array capacity check, and the other is putting the elements into the data. Let's look at the second simple start analysis, where the number of final data elements is smaller than expected when multiple threads execute in the order shown below.

After executing in this order, we can see that elementdata[n] was set only two times, and the value set by the second thread was overwritten by the previous one, and finally size=n+1. The following code is used to verify this problem.

1.3 Code Validation

First look at the following code, open 1000 threads, and call ArrayList's Add method, each thread to add 100 numbers to ArrayList, if the program is executed normally should be output:

list size is :10000  

The code is as follows:

private static list<integer> List = new arraylist<integer> ();    private static Executorservice Executorservice = Executors.newfixedthreadpool (1000); private static class Increasetask extends thread{@Override public void Run () {System.out.printl            N ("ThreadId:" + thread.currentthread (). GetId () + "start!");            for (int i =0; i <; i++) {list.add (i);    } System.out.println ("ThreadId:" + thread.currentthread (). GetId () + "finished!");}} public static void Main (string[] args) {for (int i=0; i <; i++) {Executorservice.submit (new incre        Asetask ());        } executorservice.shutdown ();            while (!executorservice.isterminated ()) {try {thread.sleep (1000*10);            }catch (interruptedexception e) {e.printstacktrace ();        }} System.out.println ("All Task finished!"); System.out.println ("List size is: "+ list.size ()); }

When you execute this main method, the output is as follows:

From the above results, the final output will be less than our expectations. That is, when multithreading calls the Add method, there is an element overlay problem.

1.4 Concurrency problems for array capacity detection

In the Add method source code, we see that each time the element is added before the array capacity of the detection, add the source code called this method is as follows:

ensureCapacityInternal(size + 1);

The relevant source code for capacity detection is as follows:

private void ensureCapacityInternal(int minCapacity) {       if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {           minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);       }       ensureExplicitCapacity(minCapacity);   }private void ensureExplicitCapacity(int minCapacity) {    modCount++;    // overflow-conscious code    if (minCapacity - elementData.length > 0)        grow(minCapacity);}

The flowchart for capacity detection is as follows:

We perform an add operation with two threads to analyze concurrency issues that may occur with the expanded capacity:
When we create a new ArrayList, the capacity of the internal array container is the default capacity of 10, when we add the 10th element at the same time with two threads, if the following execution order occurs, Java.lang.ArrayIndexOutOfBoundsException exceptions may be thrown.

The second thread adds data to the array because the array has a capacity of 10, and this action sets the element value at the position of Index 10, so an array out-of-bounds exception is thrown.

1.5 Code validation concurrency problems for array capacity detection

Use the following code:
private static list list = new ArrayList (3);

    private static ExecutorService executorService = Executors.newFixedThreadPool(10000);    private static class IncreaseTask extends Thread{        @Override        public void run() {            System.out.println("ThreadId:" + Thread.currentThread().getId() + " start!");            for(int i =0; i < 1000000; i++){                list.add(i);            }            System.out.println("ThreadId:" + Thread.currentThread().getId() + " finished!");        }    }    public static void main(String[] args){        new IncreaseTask().start();        new IncreaseTask().start();    }

After executing the main method, we can see that the console output is as follows:

1.6 ArrayList other ways to explain

Other methods in ArrayList that include operations on shared variables also have concurrency security issues, which need to be analyzed in accordance with the above analysis methods.

ArrayList source code and multithreading Security Problem analysis

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.