Home Java javaTutorial Is arraylist thread safe?

Is arraylist thread safe?

Jun 05, 2019 am 11:58 AM
arraylist

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<String> list1 = new ArrayList<String>();// 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.
    }
}
Copy after login

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<Map<String,Object>> data=Collections.synchronizedList(newArrayList<Map<String,Object>>());
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to check if ArrayList contains a certain element in Java? How to check if ArrayList contains a certain element in Java? Sep 03, 2023 pm 04:09 PM

You can use the contains() method of the List interface to check whether an object exists in the list. contains() method booleancontains(Objecto) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null?e==null:o.equals(e)). Parameter c - the element whose presence in this list is to be tested. Return Value Returns true if this list contains the specified element. Throws ClassCastException - if the specified element's type is incompatible with this list (optional). NullP

Remove elements from ArrayList using java's ArrayList.remove() function Remove elements from ArrayList using java's ArrayList.remove() function Jul 24, 2023 pm 01:21 PM

Use java's ArrayList.remove() function to remove elements from an ArrayList. In Java, ArrayList is a commonly used collection class used to store and operate a set of elements. The ArrayList class provides many methods to add, delete, modify, and query elements in the collection. One of the more frequently used methods is remove(), which can remove elements from an ArrayList. The remove() method of ArrayList has two overloaded forms: one

What is the reason why the initial capacity of ArrayList in Java is 10? What is the reason why the initial capacity of ArrayList in Java is 10? May 10, 2023 pm 02:19 PM

Why is the initial capacity of HashMap 16? When talking about the initialization capacity of ArrayList, we must first review the initialization capacity of HashMap. Taking the Java8 source code as an example, there are two relevant factors in HashMap: initialization capacity and loading factor: /***Thedefaultinitialcapacity-MUSTbeapoweroftwo.*/staticfinalintDEFAULT_INITIAL_CAPACITY=1>1);if(newCapacity-minCapacity0)newCapacity=hugeCapacity

Use java's ArrayList.clear() function to clear the elements in the ArrayList Use java's ArrayList.clear() function to clear the elements in the ArrayList Jul 24, 2023 pm 02:04 PM

Use Java's ArrayList.clear() function to clear the elements in the ArrayList. In Java programming, ArrayList is a very commonly used data structure that can dynamically store and access elements. However, in some cases, we may need to clear all elements in the ArrayList in order to reuse or free the memory. At this time, you can use the clear() function of ArrayList to achieve it. ArrayList.clear()

Java uses the contains() function of the ArrayList class to determine whether an element exists Java uses the contains() function of the ArrayList class to determine whether an element exists Jul 24, 2023 pm 07:33 PM

Java uses the contains() function of the ArrayList class to determine whether an element exists. ArrayList is a very commonly used data structure in Java programming. It provides a flexible way to store and manipulate a set of data. In addition to simply adding, deleting and accessing elements, ArrayList also provides some useful methods, such as the contains() function, which is used to determine whether an element exists in the ArrayList. contains() function is A

Get unique values ​​from ArrayList in Java Get unique values ​​from ArrayList in Java Sep 04, 2023 am 08:41 AM

ArrayListisaclassofJavaCollectionFrameworkthatimplementsListInterface.Itisalinearstructurethatstoresandaccesseseachelementsequentially.Itallowsthestorageofduplicateelementshowever,thereareafewapproachesthatmayhelptogetuniquevaluesfromanArrayList.Inth

Remove specified elements from an array list in Java using the removeAll() method of the ArrayList class Remove specified elements from an array list in Java using the removeAll() method of the ArrayList class Jul 24, 2023 pm 07:16 PM

Use the removeAll() method of the ArrayList class to remove specified elements from an array list in Java. In Java, ArrayList is a very commonly used data structure used to store and manipulate a set of objects. Sometimes we need to remove specific elements from ArrayList. The ArrayList class provides the removeAll() method to help us achieve this requirement. The function of the removeAll() method is to remove the

See all articles