集合类不安全

集合类不安全

  • ConcurrentModificationException并发修改异常
  • 解决办法
    • 写入时复制
    • 使用工具类Collections
  • List不安全
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

class ListTest {

    public static void main(String[] args) {
        /**
         * 并发编程下ArrayList不安全
         * 1.List<String> list = new Vector<>();
         * 2.List<String> list = Collections.synchronizedList(new ArrayList<>());
         * 3.List<String> list = new CopyOnWriteArrayList<>();
         */

        // CopyOnWrite 写入时复制
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }
}
  • Set不安全
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

class SetTest {
    public static void main(String[] args) {
        /**
         * 1.Set<String> set = Collections.synchronizedSet(new HashSet<>());
         * 2.Set<String> set = new CopyOnWriteArraySet<>();
         */
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }
}
  • HashSet底层是HashMap
public HashSet() {
    map = new HashMap<>();
}

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
  • HashMap不安全
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

class MapTest {
    public static void main(String[] args) {
        // 默认等价与new HashMap<>(16, 0.75); 初始化容量和加载因子
        Map<String, String> map = new ConcurrentHashMap<>();

        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}
posted @ 2021-10-30 15:04  n1ce2cv  阅读(26)  评论(0编辑  收藏  举报