Difference between ArrayList and CopyOnWriteArrayList
There are four concrete implementation of List interface:-
- Vector
- ArrayList
- LinkedList
- CopyOnWriteArrayList
Different between Vector,ArrayList and LinkedList is quite clear but
difference between ArrayList and CopyOnWriteArrayList doesn’t seems to
be clear at first glance. Here I am trying to explain between difference
between ArrayList and CopyOnWriteArrayList , with one simple
example.As we all know ArrayList is not thread safe so any simultaneous
thread can access and modify the content of list simultaneously.Here
lies the dangerous, ConcurrentModificationException. When one thread is
Iterating over an ArrayList and any other thread(which may be the same
thread) modify the content of list and when we again call next() on the
iterator ,we get this exception. Which means that no thread can modify
the ArrayList while an Iterator is iterating over this. We can solve
this by surrounding the code that try to modify this list in a
synchronized block with some lock so that the thread trying to modify
the ArrayList wait for the iterator to complete.
This seems simple solution but not a efficient one where there are
many threads iteration over an ArrayList because each thread have to
wait for a considerable time.
Another possible solution could be to use CopyOnWriteArrayList
instead of ArrayList. This is same as ArrayList with one difference. All operations that change the contents of a
CopyOnWriteArrayList
collection cause the underlying array to be replaced with a copy of
itself before the contents of the array are changed. Any active
iterators will continue to see the unmodified array, so there is no need
for locks. Iterators created by a
CopyOnWriteArrayList
object cannot change the underlying array. Though these iterators do
have methods for changing the underlying collection, their
implementations throw an
UnsupportedOperationException
instead of modifying the underlying collection.
Lets consider first case when we modify an ArrayList while an Iterator is traversing it:-
import java.util.*;
import java.util.concurrent.*;
import java.math.*;
class test{
public final static void main(String args[]){
List list= new ArrayList();
list.add("vivek");
list.add("kumar");
Iterator i =list.iterator();
while(i.hasNext()){
System.out.println(i.next());
list.add("abhishek");
}
}
}
Output:-
vivek
Exception in thread “main”
java.util.ConcurrentModificationExceptionat
java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)
at test.main(test.java:15)
Explanation:
As we have modified the ArrayList
after displaying first element, it will throw a
ConcurrentModificationException at when we call next() next time.
Now see the same program with CopyOnWriteArrayList:-
import java.util.*;
import java.util.concurrent.*;
import java.math.*;
class test{
public final static void main(String args[]){
CopyOnWriteArrayList list = new CopyOnWriteArrayList();
list.add("vivek");
list.add("kumar");
Iterator i =list.iterator();
while(i.hasNext()){
System.out.println(i.next());
list.add("abhishek");
}
System.out.println("After modification:");
Iterator i2 =list.iterator();
while(i2.hasNext()){
System.out.println(i2.next());
}
}
}
Output:-
E:\>java test
vivek
kumar
After modification:
vivek
kumar
abhishek
abhishek
vivek
kumar
After modification:
vivek
kumar
abhishek
abhishek
Explanation:-
We did not get any ConcurrentModificationExceptionat as CopyOnWriteArrayList
keeps a copy of original List and iterate over this. The new value
which has been added is merged to copy of orignal array only after
Iteration is over.
We can not use iterator of CopyOnWriteArrayList to modify the List.
Lest consider a normal ArrayList and try to modify the list using iterator.
import java.util.*;
import java.util.concurrent.*;
import java.math.*;
class test{
public final static void main(String args[]){
ArrayList list = new ArrayList();
list.add("vivek");
list.add("kumar");
Iterator i =list.iterator();
while(i.hasNext()){
System.out.println(i.next());
i.remove();
}
System.out.println("After modification:");
Iterator i2 =list.iterator();
while(i2.hasNext()){
System.out.println(i2.next());;
}
}
}
Output:-
vivek
kumar
After modification:
Explanation:-
we can use iterator’s method (remove) to modify the list. Now check for CopyOnWriteArrayList
import java.util.*;
import java.util.concurrent.*;
import java.math.*;
class test{
public final static void main(String args[]){
CopyOnWriteArrayList list = new CopyOnWriteArrayList();
list.add("vivek");
list.add("kumar");
Iterator i =list.iterator();
int j=0;
while(i.hasNext()){
System.out.println(i.next());
list.add("abhishek");
i.remove();
}
}
}
Output:-
vivek
Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWr
iteArrayList.java:937)
at test.main(test.java:17)
Explanation:-
we cannot use iterator method to modify the elements of CopyOnWriteArrayList
分享到:
相关推荐
difference between ArrayList and LinkedList?` LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements...
Java并发容器CopyOnWriteArrayList是Java并发包中提供的一个并发容器,实现了线程安全且读操作无锁的ArrayList,写操作则通过创建底层数组的新副本来实现。这种读写分离的并发策略使得CopyOnWriteArrayList容器允许...
在这个主题中,我们将深入探讨如何在JNI中操作ArrayList对象并添加一个int类型的数据。 首先,我们需要理解ArrayList在Java中的本质。ArrayList是Java集合框架中的一个重要类,它实现了List接口,用于存储可变大小...
ArrayList是一种以数组实现的List,它实现了List, RandomAccess, Cloneable, Serializable接口。 实现List接口表示它可以支持删除、添加和查找等操作。 实现RandomAccess接口表示它可以支持随机访问(强调一点,并不...
如果需要线程安全,可以考虑使用`Collections.synchronizedList()`将ArrayList转换为线程安全的列表,或者使用`CopyOnWriteArrayList`类。 ArrayList的容量会随着元素数量的增加自动扩展。默认情况下,当容量达到...
如果需要线程安全,可以选择使用`java.util.concurrent.CopyOnWriteArrayList`。 4. 常用方法: - `add(E element)`: 在列表末尾添加一个元素。 - `add(int index, E element)`: 在指定位置插入一个元素。 - `...
如果需要在多线程环境下使用,可以考虑使用`Collections.synchronizedList`方法对`ArrayList`进行同步,或者使用`CopyOnWriteArrayList`。 4. **效率比较**:相比于`LinkedList`,`ArrayList`在插入和删除元素时...
此外,对于大数据量的情况,考虑使用并发集合,如ConcurrentLinkedQueue或CopyOnWriteArrayList,以提高多线程环境下的性能。 总的来说,理解ArrayList和LinkedList的基本特性和应用场景,以及如何处理与之相关的...
这种情况下,可以通过诸如Collections.synchronizedList等包装器方法,或者使用CopyOnWriteArrayList等线程安全的替代实现来保证线程安全。 ArrayList提供了三种构造方法。一种是无参构造方法,默认初始容量为10;...
在.NET框架中,ArrayList和DataTable是两种常用的集合类,它们分别代表了两种不同的数据存储方式。ArrayList是一个基于对象数组的动态大小的列表,而DataTable则是一个内存中的表格数据结构,通常用于存储和操作关系...
如果需要线程安全的列表,应使用`CopyOnWriteArrayList`。 7. **ArrayList与LinkedList的比较** - ArrayList更适合于随机访问,插入和删除在中间位置较慢。 - LinkedList适合于频繁的插入和删除,但随机访问性能...
一个C++(Ubuntu16.04+QT5.9.1)通过JNI,调用JAVA类及方法的示例。通过JNI传递和返回多种类型的参数,boolean ,int,String,ArrayList,ArrayList嵌套ArrayList<ArrayList<String>>等。
首先,ArrayList是.NET Framework中的一个类,它继承自System.Collections.ArrayList,主要用于存储动态大小的可变数组。ArrayList可以存储任何类型的对象,非常灵活,但不提供类型安全。在C#中,我们通常更推荐使用...
### C# 中 Array、ArrayList 和 List 的区别 在C#编程语言中,处理集合数据时,程序员经常需要根据实际需求选择合适的集合类型。本文将详细解释C#中Array、ArrayList和List之间的区别,并通过示例代码帮助理解这些...
### ArrayList的使用详解 #### 一、什么是ArrayList? `ArrayList`是.NET框架中提供的一种动态数组类型,它属于`System.Collections`命名空间。与普通的数组相比,`ArrayList`具有更强大的功能,比如它可以动态地...
C# ArrayList是一个重要的数据结构,它是.NET框架早期版本中用于动态数组存储的类。这个类在System.Collections命名空间中,提供了灵活的大小调整和数据管理功能。ArrayList在C#编程中扮演了重要的角色,尤其在处理...
对于并发场景,可以使用CopyOnWriteArrayList(线程安全的ArrayList变体)和ConcurrentHashMap(线程安全的HashMap变体)。 总之,ArrayList和HashMap是Java集合框架中的重要组件,理解它们的工作原理和适用场景,...
ArrayList类是Java编程语言中一个常用的集合类,它属于Java集合框架的一部分,位于`java.util`包中。ArrayList是一个基于数组实现的动态列表,可以存储任何类型的数据,并且支持动态扩容。在本实例中,我们将深入...
在C语言中,ArrayList是一种常见的数据结构,它模拟了Java或.NET等高级语言中的动态数组。ArrayList提供了在数组中添加、删除和查找元素的便利操作,而无需预先知道数组的大小。下面,我们将深入探讨如何用C语言实现...
如果需要在并发环境中使用,可以选择使用Collections.synchronizedList()方法将ArrayList转换为线程安全的列表,或者使用并发集合如CopyOnWriteArrayList。 ArrayList的效率特点在于随机访问速度快,因为可以通过...