概述
CopyOnWriteArrayList用于替代同步List,在某些情况下有更好的并发性能,并且在迭代时不需要加锁或复制。在每次修改的时候都会创建并重新发布一个新的容器副本。
下面是源码:
//添加元素,会加锁,创建一个新的对象,原引用指向新对象
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
//获取元素,不加锁
private E get(Object[] a, int index) {
return (E) a[index];
}
public E get(int index) {
return get(getArray(), index);
}
优点:多个线程可以同时对这个容器进行迭代,而不会相互干扰或者与修改容器的线程互相干扰,即不会抛出ConcurrentModificationException,并且返回的元素与迭代器创建时的元素完全一致,而不必考虑之后修改带来的影响。
缺点:
1.在添加元素时会创建副本,如果副本占用内较大,会增加gc,严重可能会影响相应时间。
2.数据无法保证实时性,可能读到的还是老的数据。
下面贴上测试代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author wanting
*
*/
public class ListPerformanceTest {
// 线程数
private static int threadNum;
// 初始容量
private static int initCapacity;
// 循环次数
private static int loop;
private static CountDownLatch startLatch;
private static CountDownLatch endLatch;
private static List<String> cowList;
// 耗时
private volatile static double cowListTotalCost;
private static List<String> syncList;
// 耗时
private volatile static double syncListTotalCost;
public ListPerformanceTest(int threadNum, int initCapacity, int loop) {
ListPerformanceTest.initCapacity = initCapacity;
ListPerformanceTest.threadNum = threadNum;
ListPerformanceTest.loop = loop;
startLatch = new CountDownLatch(threadNum);
endLatch = new CountDownLatch(threadNum);
cowList = new CopyOnWriteArrayList<>(new ArrayList<>(initCapacity));
syncList = Collections.synchronizedList(new ArrayList<>(initCapacity));
initList();
}
public void initList() {
for (int i = 0; i < initCapacity; i++) {
cowList.add(i + "");
syncList.add(i + "");
}
}
public static void testPerformance(List<String> list) {
long t1 = System.nanoTime();
Random random = new Random();
for (int i = 0; i < loop; i++) {
int index = random.nextInt(initCapacity);
list.get(index);
}
long t2 = System.nanoTime();
double costTime = (t2 - t1) / 1000000d;
if (list instanceof CopyOnWriteArrayList) {
cowListTotalCost = cowListTotalCost + costTime;
} else {
syncListTotalCost = syncListTotalCost + costTime;
}
// System.out.println(list.getClass() + "耗时:" + costTime + "秒");
}
public static void addEle(String element) {
cowList.add(element);
syncList.add(element);
}
public static void main(String[] args) {
ListPerformanceTest listPerformanceTest = new ListPerformanceTest(500, 100000, 10000);
ExecutorService pool = Executors.newFixedThreadPool(threadNum);
for (int i = 1; i <= threadNum; i++) {
final int flag = i;
pool.submit(new Runnable() {
@Override
public void run() {
try {
startLatch.await();
//if (flag % 2 == 0) {
//addEle(flag + "");
// }
testPerformance(cowList);
testPerformance(syncList);
} catch (Exception e) {
e.printStackTrace();
}
endLatch.countDown();
}
});
startLatch.countDown();
}
try {
endLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("cowz总耗时:" + cowListTotalCost + "微秒,平均耗时:" + (cowListTotalCost / (threadNum * 1.0) + "微秒"));
System.out
.println("sync总耗时:" + syncListTotalCost + "微秒,平均耗时:" + (syncListTotalCost / (threadNum * 1.0) + "微秒"));
pool.shutdown();
}
总结:适合用于迭代操作远远多于修改操作时。随着并发量增加或者迭代次数增加,CopyOnWriteArrayList性能要优于同步List。
最后
以上就是潇洒爆米花为你收集整理的CopyOnWriteArrayList简单使用及性能测试的全部内容,希望文章能够帮你解决CopyOnWriteArrayList简单使用及性能测试所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复