List common classes and their respective advantages and disadvantages can refer to https://blog.csdn.net/weixin_39883065/article/details/111197724
local environment
java version: 1.8.0_161
window information:
test code
The following code tests the List thread-safe class Vector, Collections.synchronizedList(List list), CopyOnWriteArrayList
The test adds 100 million data, opens 100 threads, and inserts 1 million data per thread
public class TestList {
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
// 线程不安全
// List<Integer> list = new ArrayList<>();
// 线程安全 100000000 耗时 27357
// List<Integer> list = new Vector<>();
// 线程安全 100000000 耗时 22023
List<Integer> list = Collections.synchronizedList(new ArrayList<>());
// 线程安全 100000000 耗时
//List<Integer> list =new CopyOnWriteArrayList<>();
int threadNum = 100;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 1000000; j++) {
list.add(j);
}
countDownLatch.countDown();
});
thread.start();
}
countDownLatch.await();
long endTime = System.currentTimeMillis();
System.out.println(list.size());
System.out.println(list.getClass()+"耗时: "+(endTime-startTime));
}
}
ArrayList Result
Collections.synchronizedList(List list) Result
Vector Result
CopyOnWriteArrayList Result, no result yet, run for more than 20 minutes, give up the test
Summarize
- In the case of more reads and less writes, it is recommended to use the CopyOnWriteArrayList method
- In the case of less reading and more writing, it is recommended to use Collections.synchronizedList() and Vector. There is not much difference