JUC class (ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet, auxiliary class) ReentrantLock and Synchronized

JUC class

hashMap is thread-unsafe and cannot be operated concurrently

HashTable is thread-safe and has synchronized modification. Adding the lock directly to put() is inefficient. It is equivalent to locking the entire hash table. It can be used in low concurrency situations. Exclusive lock

ConcurrentHashMap

ConcurrentHashMap is thread-safe. It adopts the lock segmentation mechanism and does not lock the entire hash table. However, segmented locks are not used after jdk8 (create a lock flag object for each position), and it is implemented using CAS idea + synchronized

When inserting, check whether the position corresponding to the hash table is the first node. If so, use the CAS mechanism (loop detection) to insert data into the first position.

If this position already has a value, then the first Node object is used as the lock flag to lock, using the synchronized implementation.

public class HashMapDemo {
    
    

    /*
       HashMap是线程不安全的,不能并发操作的
       ConcurrentModificationException  并发修改异常   遍历集合,并删除集合中的数据

       Hashtable 是线程安全的 public synchronized V put(K key, V value)-->独占锁
            锁直接加到了put方法上,锁粒度比较大,效率比较低
            用在低并发情况下可以

       Map<String,Integer> map = Collections.synchronizedMap(new HashMap<>());
       ConcurrentHashMap
     */
    public static void main(String[] args) {
    
    

        ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap<>();
        //模拟多个线程对其操作
        for (int i = 0; i < 20; i++) {
    
    
                 new Thread(
                     ()->{
    
    
                       map.put(Thread.currentThread().getName(), new Random().nextInt());
                         System.out.println(map);
                     }
                 ).start();
        }

    }
}

CopyOnWriteArrayList

Read and write are completely separated, no locking is required for read operations, and reading does not affect the data.

The write operation is locked, and the write operation does not affect the read operation. If two threads are added at the same time, they will be mutually exclusive.

When adding, first make a copy of the original array.

Then add the data to the copy without affecting the read operation

Finally replace the original array with a copy

CopyOnWriteArraySet

is one that does not allow duplicate data

The underlying implementation is CopyOnWriteArrayList, which cannot store duplicate data

Auxiliary class CountDownLatch

Make a thread wait for other threads to finish executing before executing

Equivalent to a decrementing thread counter

First set a number. When a thread ends, decrease it by one until it reaches 0. Close the counter and the thread will be executed.

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-wS5P0aFG-1642418593327) (C:\Users\Cloud\AppData\Roaming\Typora\typora-user-images\ 1642401770485.png)]

Auxiliary class CyclicBarrier

Let a group of threads be blocked when they reach a barrier. The barrier will not open until the last thread reaches the barrier.

It is an adding counter. When the number of threads reaches the specified number, the door will be opened and released.

lock in java

There are many lock nouns. These classifications do not all refer to locks. Some refer to the characteristics of the lock, and some refer to the design of the lock.

Some refer to the status of the lock. The content summarized below is a certain explanation of the noun of each lock.

Optimistic lock/pessimistic lock

Optimistic locking: It means no locking , and it is believed that concurrent modifications are no problem. For example, the CAS mechanism is designed to be implemented in a lock-free way. It is suitable for many read operations.

Pessimistic lock: It is believed that problems will occur in concurrent operations and locking is needed to ensure safety. Suitable for many write operations

Reentrant lock

Reentrant Lock

Deadlock can be avoided to a certain extent

When a synchronized method calls another method that uses the same lock as it

Even if there is no release in the outer method, you can enter another synchronized method.

Reentrant Lock and synchronized are both reentrant locks

eg: The setA() and setB() methods use the same lock. After entering the setA method, the lock is obtained and the setB method is called. If the lock is not reentrant, the lock is not released in the setA() method. The setB() method It will not be executed by the current thread. If it is a reentrant lock, the setB() method can be executed smoothly without causing a deadlock.

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-p1ee1woE-1642418593330) (C:\Users\Cloud\AppData\Roaming\Typora\typora-user-images\ 1642417471732.png)]

ReadWriteLock (ReadWriteLock)

It is a specific lock implementation. Reading and writing are two locks and can be used separately.

segment lock

It is a locking idea, not an actual lock implementation. It uses segmented locking to reduce the granularity of the lock and thereby improve efficiency.

SpinLock

It is not a lock implementation. It uses spin (loop retry) to try to obtain execution rights and will not let the thread enter a blocked state. It is suitable for situations where the lock time is short.

CAS is implemented based on spin lock

shared lock

Locks that can be shared by multiple threads

The read lock of ReadWriteLock is shared, and multiple threads can read data at the same time.

exclusive lock

Also called a mutex lock, only one thread can acquire the lock at a time

Reentrant Lock, synchronized, ReadWriteLock's write lock is an exclusive lock

The implementation in ReadWriteLock uses synchronized queues. For example, the read thread obtains the resource, sets the standard state to used, and then adds other write threads to a queue to wait.

AQS(AbstractQueuedSynchronizer)

Maintain a queue for waiting threads to queue up.

fair lock

It will maintain a waiting list of threads and execute the threads at a time.

Reentrant Lock is unfair by default. You can specify whether it is a fair lock or an unfair lock through the construction method when creating it.

unfair lock

There is no queue. Once the lock is released, threads begin to preempt. Whoever seizes the right to execute will execute first.

lock status

No lock/biased lock/lightweight lock/heavyweight lock

Biased lock: refers to that only one thread is constantly acquiring the lock, which makes it easier to acquire the lock.

Lightweight lock: When the lock is a biased lock and is accessed by another thread, the biased lock will be upgraded to a lightweight lock. If it is a lightweight lock, the waiting thread will not enter the blocking state and use spin mode. Try to acquire the lock again to improve efficiency.

Heavyweight lock: When the lock status is a lightweight lock, if some threads spin too many times, or there are a large number of thread accesses, the lock status will be upgraded to a heavyweight lock. At this time, threads that have not obtained the lock will no longer automatically Spin, enter blocking state

ReentrantLock

It is a class, it can only modify the code block to display the lock, add it manually and release it manually.

It is a class-level control, using CAS+AQS. It is a reentrant lock, which can be a fair lock or not.

A lock state is maintained inside the class. Once a thread preempts it, the state is changed to 1, and other threads enter the queue and wait for the lock to be released (when it is a fair lock). Once the lock is released, then Wake up the head node and start trying to obtain the lock

synchronized

It is a reentrant lock and an unfair lock.

It is a keyword that can modify code blocks or methods.

It is an implicit lock, which can automatically acquire and release the lock.

synchronized implements locking and releasing locks at the instruction level

There is an entry into the monitor +1 object headlock flag is used

perform tasks

Exit the monitor -1 When equal to 0, the object head lock mark is changed to no lock

Guess you like

Origin blog.csdn.net/crraxx/article/details/122546568