The collection class is not secure

The List is not safe

package com.chao.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);

        // Synchronized
        List
      
        List = new Vector<>(); * 2, a List < String > List = Collections. SynchronizedList (new ArrayList < > ()); * 3, List
       
         List = new CopyOnWriteArrayList<>(); * /
       
      
        //CopyOnWrite An optimization strategy in the computer programming field of copy-on-write COW
        // When multiple threads call,list, read, fixed, write (overwrite)
        // Avoid overwriting while writing, causing data problems!

        // Read and write separate MyCat
        // Where is CopyOnWriteArrayList compared to Vector Nb?

        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(); }}}Copy the code

Learning methods recommended: 1, first will use, 2, shop around, looking for other solutions, 3, source analysis!

The Set is not safe

package com.chao.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/** * Java. Util. ConcurrentModificationException * 1, Set the < String > Set = Collections. SynchronizedSet (new HashSet < > ()); * 2, Set
      
        Set = new CopyOnWriteArraySet<>(); * /
      
public class SetTest {
    public static void main(String[] args) {
        //Set<String> set = new HashSet<>();
        //Set<String> set = Collections.synchronizedSet(new HashSet<>());
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 1; i <=30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0.5)); System.out.println(set); },String.valueOf(i)).start(); }}}Copy the code

What’s underneath a hashSet?

public HashSet(a) {
    map = new HashMap<>();
}

// Add set is essentially a map key that cannot be repeated!
public boolean add(E e) {
   return map.put(e, PRESENT)==null;
 }

private static final Object PRESENT = new Object(); // Constant value!
Copy the code

IO, collection classes, common classes

The Map is not safe

Review the basic operations of Map