Unsafe collection and its solution

Time:2021-9-21

List is not safe

package com.hudu.demo01.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

//Java.util.concurrentmodificationexception concurrent modification exception
public class ListTest {
    public static void main(String[] args) {
//        List<String> list = Arrays.asList("1", "2", "3");
//        list.forEach(System.out::println);

        //And sending ArrayList is not safe
        /**
         *Solution
         * 1、Vector<String> list2 = new Vector<>();
         * 2、List<String> list3 = Collections.synchronizedList(new ArrayList<>());
         * 3、List<String> list4 = new CopyOnWriteArrayList<>();
         */
        ArrayList<String> list1 = new ArrayList<>();
        Vector<String> list2 = new Vector<>();
//        List<String> list3 = Collections.synchronizedList(new ArrayList<>());
        //Copyonwrite is an optimization strategy in the field of copy cow computer programming
        //When multiple threads call, the list is fixed when reading and written (overwritten)
        //Avoid overwriting when writing, resulting in data problems
        //Read write separation
        //Where is copyonwritearraylist better than vector?

        List<String> list4 = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                list4.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list4);
            },String.valueOf(i)).start();
        }
    }
}

Set is not safe

/**
 *The same can be proved: java.util.concurrentmodificationexception
 *Solution:
 * 1、Set<String> set1 = Collections.synchronizedSet(new HashSet<>());
 * 2、
 */
public class SetTest {
    public static void main(String[] args) {
//        HashSet<String> set = new HashSet<>();
        Set<String> set1 = Collections.synchronizedSet(new HashSet<>());

        Set<String> set2 = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set1.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set1);
            }).start();
        }
    }
}
What is the bottom layer of HashSet?
public HashSet() {
        map = new HashMap<>();
    }

//The essence of add set is that map keys cannot be repeated
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
//Constant value of present
private static final Object PRESENT = new Object();

Map is not secure

Review the basic operation of map

Unsafe collection and its solution

//ConcurrentModificationException
public class MapTest {
    public static void main(String[] args) {
        //Is that so? No, you don't use HashMap at work
        //What is the default equivalent of new HashMap < > (16,0.75);
//        HashMap<String, String> map = new HashMap<>();
        //Load factor, initialization capacity

//        Collections.synchronizedMap()
        Map<String, String> map2 = new ConcurrentHashMap<>();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                map2.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
                System.out.println(map2);
            },String.valueOf(i)).start();
        }
    }
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]