ConcurrentHashMap替代HashMap、HashTable
ConcurrentHashMap
package com.yuzhenc.collection;
import java.util.concurrent.ConcurrentHashMap;
public class Test22 {
public static void main(String[] args) {
ConcurrentHashMap<String,Integer> concurrentHashMap = new ConcurrentHashMap<>();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++) {
concurrentHashMap.put("test" + j , j);
}
long endTime = System.currentTimeMillis();
System.out.println("ConcurrentHashMap一共需要的时间:" + (endTime - startTime));
}
}).start();
}
}
}
HashMap
package com.yuzhenc.collection;
import java.util.HashMap;
public class Test23 {
public static void main(String[] args) {
HashMap<String,Integer> hashMap = new HashMap<>();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++) {
hashMap.put("test" + j , j);
}
long endTime = System.currentTimeMillis();
System.out.println("hashMap一共需要的时间:" + (endTime - startTime));
}
}).start();
}
}
}
Hashtable
package com.yuzhenc.collection;
import java.util.Hashtable;
public class Test24 {
public static void main(String[] args) {
Hashtable<String,Integer> hashtable = new Hashtable<>();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
for (int j = 0; j < 1000000; j++) {
hashtable.put("test" + j , j);
}
long endTime = System.currentTimeMillis();
System.out.println("hashtable一共需要的时间:" + (endTime - startTime));
}
}).start();
}
}
}
COW并发容器(Copy On Write容器)
- 向容器中添加元素时,先将容器进行Copy复制出一个新容器,然后将元素添加到新容器中,再将原容器的引用指向新容器;并发读的时候不需要锁定容器,因为原容器没有变化,所以可以读取原容器中的值,使用的是一种读写分离的思想;
- CopyOnWrite容器只能保证数据的最终一致性,不能保证数据实时一致性,所以如果你希望写入的的数据,马上能读到,请不要使用CopyOnWrite容器;
- 适合读多写少,如果一万个线程都添加操作,都在集合中添加数据,那数组不断复制,长度不断+1,那JVM肯定一直往上飙升,用的时候肯定要评估使用场景的,由于每次更新都会复制新容器,所以如果数据量较大并且更新操作频繁则对内存消耗很高,建议在高并发读的场景下使用
CopyOnWriteArrayList和CopyOnWriteArraySet
package com.yuzhenc.collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
public class Test25 {
public static void main(String[] args) {
CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add("Lili");
copyOnWriteArrayList.add("Amy");
System.out.println(copyOnWriteArrayList);
copyOnWriteArrayList.addIfAbsent("Lili");
System.out.println(copyOnWriteArrayList);
copyOnWriteArrayList.add("Lili");
System.out.println(copyOnWriteArrayList);
CopyOnWriteArraySet<String> copyOnWriteArraySet = new CopyOnWriteArraySet<>();
copyOnWriteArraySet.add("Lili");
copyOnWriteArraySet.add("Amy");
copyOnWriteArraySet.add("Lili");
System.out.println(copyOnWriteArraySet);
}