Home  >  Article  >  Java  >  Is arraylist thread safe?

Is arraylist thread safe?

(*-*)浩
(*-*)浩Original
2019-06-05 11:58:4310895browse

What is thread unsafe:

Thread safety means that when multi-threads access, a locking mechanism is used. When a thread accesses certain data of this class, it is protected. Other threads cannot access it until this thread has finished reading, and then other threads can use it. There will be no data inconsistency or data pollution. Thread insecurity means that data access protection is not provided. It is possible that multiple threads may change data successively, causing the data obtained to be dirty data.

Is arraylist thread safe?

An ArrayList, when adding an element, it may be completed in two steps:

1 . Store this element at the location of Items[Size];

2. Increase the value of Size. (Recommended learning: Java Video Tutorial)

In the case of single-threaded operation, if Size = 0, after adding an element, the element will be at position 0, and Size=1;

If it is a multi-threaded situation, for example, there are two threads, thread A first stores the element at position 0. But at this time, the CPU schedules thread A to pause, and thread B gets a chance to run. Thread B also adds elements to this ArrayList, because Size is still equal to 0 at this time (note that we assume that adding an element requires two steps, and thread A only completed step 1), so thread B also adds elements to Stored at location 0. Then both thread A and thread B continue to run, both increasing the value of Size.

Okay, now let's take a look at the situation of ArrayList. There is actually only one element, stored at position 0, but Size is equal to 2. This is "thread unsafe".

Sample program:

package test;
 
importjava.util.ArrayList;
 
import java.util.List;
public class ArrayListInThread implements Runnable{
    List list1 = new ArrayList();// not thread safe
    publicvoid run() {
        try {
           Thread.sleep((int)(Math.random() * 2));
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        list1.add(Thread.currentThread().getName());
    }
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup group = new ThreadGroup("mygroup");
        ArrayListInThread t = new ArrayListInThread();
        for (int i = 0; i < 10000; i++) {
            Thread th = new Thread(group, t,String.valueOf(i));
            th.start();
        }
        while (group.activeCount() > 0) {
            Thread.sleep(10);
        }
        System.out.println();
        System.out.println(t.list1.size()); // it should be 10000 if thread safecollection is used.
    }
}

How to solve thread insecurity?

One: Use the synchronized keyword, which everyone should be familiar with, so I won’t explain it;

Two: Use Collections.synchronizedList(); The usage method is as follows:

Suppose the code you create is as follows: List>data=new ArrayList>();

Then in order to solve this thread safety problem you You can use Collections.synchronizedList() like this, such as:

List> data=Collections.synchronizedList(newArrayList>());

Nothing else has changed, and the method used is almost the same as ArrayList. You can refer to the api document;

More Java related For technical articles, please visit the Java Development Tutorial column to learn!

The above is the detailed content of Is arraylist thread safe?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn