About the lock between Java and thread communication

Fair locking and non-locking fair

And creation of ReentrantLock contract may specify boolean type constructor fair or unfair lock latch, lock default non-fair

Difference between the two:

公平锁: In a concurrent environment, each thread will first acquire the lock when the lock maintenance view this queue, if it is empty, or the current thread is waiting on a queue, it is holding the lock, otherwise it will be added to the waiting queue in the future we will be waiting to be taken from the queue to the FIFO in accordance with the rules.

非公平锁: Compare rude unfair lock up directly try to have a lock, if the attempt fails, waits in a manner similar fair locks in the queue to be taken.

For java ReentrantLock terms, specified by the constructor of the lock is fair locks 默认是非公平锁. Lock unfair advantage from content with throughput greater than the fair locks.

For synchronized, the fair is also a non-lock

Reentrant lock (lock recursion)

Reentrant lock called recursive lock, typical reentrant locks ReentrantLock / Synchronized. Refers to the outer function after unification orange to acquire a lock, the inner metric function can still acquire the lock code, the same time a thread acquires the lock of the outer layer of the method, the method will automatically get locked into the inner layer
is to say, thread can enter any code block that he already has a lock synchronized with the.

    public synchronized void method01(){
        method02();
    }
    public synchronized void method02(){
        
    }
复制代码

As the above code, if a thread has a lock method01, then automatically have lock method02, so look, reentrant lock biggest role is to avoid deadlock

Spinlocks

Can refer to the article describes the CAS means locking

    public final int getAndSetInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var4));

        return var5;
    }
复制代码

Spin lock refers to the thread acquires the lock will not be blocked immediately, instead of using a circular fashion to try to acquire the lock until successful so far, no blocking of a similar wait, this benefit is to reduce the consumption of thread context switching, the drawback is that the cycle will consume CPU

Manually implement a spin lock:

public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread +": come in lock");
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }


public void unLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread + ": come in unlock");
        while (!atomicReference.compareAndSet(thread,null)){

        }
    }
复制代码

When A thread calls myLock, thread is null, so atomicReference.compareAndSet (null, thread) established negated out of the loop, then the thread is A Thread AtomicReference, but also when the calling thread myLock B method, since the expected value is null actually a thread, the result does not hold, it has been circulating in the while; a thread then call the unlock method, the expected value is a own thread, and then set to null, returns true then negated, out of the loop, B thread constantly mylock in circulation, suddenly read the expected value is null, and meet their needs, and then out of the loop, then lock success.

Exclusive lock (write lock) / share lock (read lock) / mutex

Exclusive lock: The lock can only be held by a thread, ReentrantLock and Synchronized are exclusive lock
shared locks: The locks can be held by multiple threads. ReentrantReadWriteLock the read lock is a shared lock, write lock is an exclusive lock it. Shared lock to read lock ensures very efficient concurrent read, write, write, read, write processes are mutually exclusive.

CountDownLatch

Let some other thread blocks until the thread is finished after a series of operations to be awakened CountDownLatch there are two main methods, when one or more thread calls await method, the calling thread will be blocked. Other thread calls countDown method will counter by 1 (method countDown calling thread will not be blocked), when the counter value becomes zero, the blocked thread can be awakened due invoked await, continue.

CyclicBarrier

Wie CyclicBarrier barrier means may be recycled. The main function is to allow a group of thread reaches a point barrier (also called synchronization point) is blocked when it until the last thread reaches the barrier, the barrier will open the door, the barrier will continue to work to intercept thread, the thread into the barrier by CyclicBarrier of the await () method. demo: an assembly of seven to summon Dragon Pearl

Semaphore

Semaphore semaphore, mainly for two purposes, one for a plurality of mutually exclusive use of shared resources, and the other for controlling the number of concurrent threads.

Synchronized and Lock What is the difference? With a new lock What are the benefits

  1. An angle
    synchronized keyword belongs jvm level, by the monitorenter (bottom layer is accomplished by monitor object, wait / notify other methods rely on the monitor object, or only in the sync block synchronization process to transfer wait / notify or the like), to the monitorexit control lock lock is a specific category (java.util.concurrent.locks.lock), is api-level lock
  2. Use synchronized does not require the user to manually release the lock, when synchronized code execution after the system will automatically make the thread releases the lock occupation reentrantlock require the user to manually release the lock, if not take the initiative to release the lock, it may lead to a deadlock. Requires mating lock () and unlock () method with the try / finally statement block to complete.
  3. Whether to wait for interruptible
    synchronized not be interrupted, unless an exception or throw the normal operation of complete
    reentrantLock interruptible:
    • The method of setting the timeout tryLock (long timeout, TimeUnit unit)
    • lockInterruptibly in () to put the code block, the call interrupt () method interruptible
  4. Lock it fair
    synchronized unfair unfair lock lock reentrantlock default, the constructor can be passed if bolean lock set fair
  5. Binding multiple conditions condition synchronized not only the conditions set random notify or notifyAll reentrantlock to implement threads are grouped need to wake up wake up, you can wake up precisely, rather than synchronized, either immediately wake up a thread or threads all wake up

Guess you like

Origin juejin.im/post/5d17a496f265da1bbd4b8aea