JAVA high concurrency (JUC) collection is not safe

The first is our ArrayList:

This time we are explaining the insecurity of collections. First of all, we all know ArrayList!
First of all, we expand a few knowledge points. The bottom layer of ArrayList is an array of Object type. The initial capacity is 10 (before jdk7, after jdk8 is a null reference, it will become 10 after add, similar to the lazy loading mechanism), and its expansion method Each expansion is half of the previous one. For example, 10 will be expanded to 15, and 15 will be expanded to 22. The method used for expansion is the copyof method of Arrays. OK, then enter the topic.
Look at this code first:

List<String> list=new ArrayList<>();

Then we use Lambda expressions to generate several threads

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

An exception will be reported afterwards:
java.util.ConcurrentModificationException
Cause of
concurrent modification exception : Multi-threaded concurrency competition for uniform resources, and no locks. So what solutions do we have ? ?
method one:

 List<String> list = new Vector<>();

Vector collection, the bottom layer adds synchronized (relocking) to the add method. There are only one thread at the same time, which is inefficient, so this is why the collection is inefficient and safe.

Method Two:

Collections.synchronizedList(new ArrayList<>());

This is a static method of Connections, passing in an ArrayList.

Method three:

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

The class of this JUC package implements the List interface.
Bottom layer: volatile Object[] array
has a lock ReentrantLock in its add method :

public boolean add(E e) {
        final ReentrantLock lock = this.lock; //加锁
        lock.lock();
        try {
            Object[] elements = getArray();  //先得到老版本的集合
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

**

Then we look at the Set collection:

The same extended knowledge points, the underlying data structure of HashSet is HashMap (new HashMap() in the source code constructor), and its add method actually returns map.put(e, PRESENT )==null; PRESENT is actually an object always on, So it is actually the keys of HashMap.
The same steps:

        Set<String> set=new HashSet<>();
        for(int i=0;i<30;i++){
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

The same is an error:
java.util.ConcurrentModificationException
Solution:
Method 1:

Set<String> set=Collections.synchronizedSet(new HashSet<>());

Method Two:

 Set<String> set=new CopyOnWriteArraySet();

It is also a class in JUC, and its constructor is actually new CopyOnWriteArrayList();

Then is our Map:

Extended knowledge: The bottom layer of HashMap (unordered and no repetition) is array + linked list (one-way) + red-black tree, HashMap stores node, and node stores Key-Value. The initial capacity of HashMap is 16, and the load factor is 0.75 ( Expand the capacity when it reaches 16*0.75), the initial capacity and load factor can be changed through the constructor, and the original capacity will be doubled each time.

 Map<String, String> map = new HashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }

The same error will be reported:
java.util.ConcurrentModificationException
solution:

 Map<String, String> map = new ConcurrentHashMap();

Under the JUC package.

This time, the collection of JUC explained this time is not safe. I hope it can help you. If you have better suggestions, please leave a message!

Guess you like

Origin blog.csdn.net/Pzzzz_wwy/article/details/105960684