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.
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 0) { Thread.sleep(10); } System.out.println(); System.out.println(t.list1.size()); // it should be 10000 if thread safecollection is used. } }</string></string>
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
Then in order to solve this thread safety problem you You can use Collections.synchronizedList() like this, such as:
List<map>> data=Collections.synchronizedList(newArrayList<map>>());</map></map>
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!

一、Iterator和foreach的区别多态差别(foreach底层就是Iterator)Iterator是一个接口类型,他不关心集合或者数组的类型;for和foreach都需要先知道集合的类型,甚至是集合内元素的类型;1.为啥说foreach底层就是Iterator编写的代码:反编译代码:二、foreach与iterator时remove的区别先来看阿里java开发手册但1的时候不会报错,2的时候就会报错(java.util.ConcurrentModificationException)首

您可以利用List接口的contains()方法来检查列表中是否存在对象。contains()方法booleancontains(Objecto)如果此列表包含指定的元素,则返回true。更正式地说,如果且仅当此列表包含至少一个元素e,使得(o==null?e==null:o.equals(e)),则返回true。参数c-要测试其在此列表中是否存在的元素。返回值如果此列表包含指定的元素,则返回true。抛出ClassCastException-如果指定元素的类型与此列表不兼容(可选)。NullP

使用java的ArrayList.remove()函数移除ArrayList中的元素在Java中,ArrayList是一种常用的集合类,用于储存和操作一组元素。ArrayList类提供了许多方法来增删改查集合中的元素。其中一个使用频率较高的方法是remove(),它可以移除ArrayList中的元素。ArrayList的remove()方法有两种重载形式,一

使用Java的ArrayList.clear()函数清空ArrayList中的元素在Java编程中,ArrayList是一种非常常用的数据结构,它可以动态地存储和访问元素。然而,在某些情况下,我们可能需要清空ArrayList中的所有元素,以便重新使用或释放内存。这时,就可以使用ArrayList的clear()函数来实现。ArrayList.clear()

为什么HashMap的初始化容量为16?在聊ArrayList的初始化容量时,要先来回顾一下HashMap的初始化容量。这里以Java8源码为例,HashMap中的相关因素有两个:初始化容量及装载因子:/***Thedefaultinitialcapacity-MUSTbeapoweroftwo.*/staticfinalintDEFAULT_INITIAL_CAPACITY=1>1);if(newCapacity-minCapacity0)newCapacity=hugeCapacity

Java使用ArrayList类的contains()函数判断元素是否存在在Java编程中,ArrayList是一个非常常用的数据结构。它提供了一种灵活的方法来存储和操作一组数据。除了简单的添加、删除和访问元素之外,ArrayList还提供了一些有用的方法,例如contains()函数,用于判断元素是否存在于ArrayList中。contains()函数是A

ArrayListisaclassofJavaCollectionFrameworkthatimplementsListInterface.Itisalinearstructurethatstoresandaccesseseachelementsequentially.Itallowsthestorageofduplicateelementshowever,thereareafewapproachesthatmayhelptogetuniquevaluesfromanArrayList.Inth

使用ArrayList类的add()方法在Java中添加元素的方法ArrayList是Java中常见的集合类之一,它提供了方便的方法来管理动态长度的数组。在ArrayList中添加元素是常见的操作之一,而add()方法是实现这一操作的主要方法之一。add()方法的使用非常简单,它可以在ArrayList的末尾添加一个元素。下面是一个示例代码,演示了如何使用a


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
