Java synchronization locks and lock -synchronized

A, synchronized keyword

1, synchronized Profile

synchronized basis to achieve synchronization: java each object can be used as a lock. When the lock must be released when a thread attempts to access the synchronization code, you must first obtain the object lock, exit or throw an exception.

Forms of: block synchronization and a method for synchronizing .


2, synchronized usage scenarios

  • Method for synchronizing

public synchronized void method1(){}复制代码

The object is locked an instance when the instance of the object in the synchronization method calls from different threads, thread only get a lock, and the rest is blocked. But if the different threads to this class different instances of the object to perform this synchronization method , you will not be blocked because they use different locks.


  • Synchronization code block

synchronized(this)( //ToDo}
synchronized(普通变量){    }复制代码

Ditto


  • Static synchronous method

public synchronized static void method3(){}复制代码

This class is locked, when the different thread calls the class static synchronized method when you only have one thread to acquire a lock , the remaining thread is blocked .


  • Static code block

synchronized(Test.class){ //ToDo}
synchronized(静态变量){ //ToDo}复制代码

Ditto


3, synchronized lock escalation

There are four kinds of lock state level from low to high are: lock-free state , biased locking state , the lightweight lock and heavyweight lock

Lock can upgrade but can not downgrade, upgrade biased locking means can not be downgraded to a biased locking the lightweight lock.

  • Biased locking

The large case, there is no multi-threaded lock not only compete, but always get many times by the same thread, the thread in order to allow for lower costs introduced by the biased locking.

When one thread to access and synchronization code to acquire the lock, the lock will recording head and the object in the stack frame of the thread ID stored biased lock, after the thread exits and re-enters the synchronization lock, the lock is not required to operate and CAS unlock, but simply to test whether the head of Mark Word objects stored in the current thread of execution biased locking.

Biased locking effect is: when there is no other threads of competition, has been bias current thread, the current thread may have been executed.


  • Lightweight lock (spin locks)

Lightweight lock, lock biased by the upgrade from.

Biased locking operation in case of a thread enters a synchronized block, when added to the second thread lock contention when the lock will be upgraded to lightweight biased lock.

  • Heavyweight lock

After the expansion of the lightweight lock, the lock will be upgraded to heavyweight.

Relies on the internal lock object when the heavyweight monitor lock to achieve, and monitor and operating system dependent MutexLock (mutex) to achieve, it is also known heavyweight lock mutex (synchronized is a heavyweight lock).


Biased locking

Advantages: no additional locking and unlocking consumption

Disadvantages: there is competition thread, it will bring additional lock revocation consumption

Scene: a single thread synchronization block access to scenes

Lightweight lock

Pros: The thread does not block competition, improve the response speed of the program.

Disadvantages: does not release the CPU when spin thread

Scene: seek response time, sync blocks performed very fast.

Heavyweight lock

Advantages: competition does not use spin thread, freeing the CPU

Disadvantages: thread is blocked, the response time is slow.

Scene: pursuit of certain sync blocks long execution speed.


Two, Lock Interface

1, Lock Interface

Lock, lock objects. Before Lock the interface appears, by the synchronized keyword Java program to achieve lock function. And in the new contract and the Lock interface after Java SE5.0 to achieve lock function.

It provides synchronized keyword similar synchronization feature, but need to show to get and release locks, as the difference between the two complement the text.


Lock main interface methods:

  • void lock()

When performing the method, when the lock is in an idle state, the current thread will acquire the lock. On the contrary, if the lock has been held by another thread, the current thread to acquire the lock is prohibited.


  • boolean tryLock()

If the lock is available, get a lock, and immediately return true, otherwise false.

Difference tryLock () and Lock () are:

tryLock () just trying to get a lock, if the lock is not available , does not cause the current thread is disabled , the current thread continues to execute code down.

Lock () is sure to get a lock, if the lock is not available , it waits until the lock is not obtained, the current thread does not continue down their own.


  • void unlock()

When performing the method, the current thread holds the lock is released, the lock can only be released by the holder, if no thread holds the lock, the execution of the method may result in unexpected ways.


  • Condition newCondition()

Condition object, waiting to get notification component. The assembly and the current lock bindings, only the current thread to acquire the lock, will call to await the component () method, after the call, the current thread releases the lock.


2, Reentrantlock use

Reentrantlock very simple to use, just to show the call, to obtain synchronization lock, to release the synchronization lock.

ReentrantLock lock = new ReentrantLock(); //参数默认false,不公平锁
.....................

try {
    lock.lock(); //如果被其它资源锁定,会在此等待锁释放,达到暂停的效果
    //操作
}catch(Exception e){
   //异常处理
} finally {
    lock.unlock();  //释放锁
}复制代码

reentrantlock lock, used under conditions of high concurrent performance is much higher than the synchronized keyword.

And reentratnlock fair and unfair lock queue are based on an internally maintained locked doubly linked list , the table value node is Node each request the current thread lock.


3, ReadWriteLock Interface

ReadWriteLock main interface as follows:

public interface ReadWriteLock {
    /**
     * Returns the lock used for reading.
     *
     * @return the lock used for reading
     */
    Lock readLock();

    /**
     * Returns the lock used for writing.
     *
     * @return the lock used for writing
     */
    Lock writeLock();
}复制代码

ReadWriteLock manage a set of locks, is a read-only lock is a write lock.

Java concurrency library ReentrantReadWriteLock implements the interface and added ReadWriteLock reentrant features.


Read locks at the same time allows multiple threads to access, but the writing process to access all the reader threads and other write processes are blocked .

Write lock maintenance pair of locking, a read lock and a write lock , through the read-write lock separation , compared to the general concurrency that an exclusive lock has greatly improved.


Several features ReentrantReadWriteLock read-write lock :

  • Selective fair
  • Reentrant
  • Lock downgrade


Examples of read-write locks (program from the blog.csdn.net/canot/artic…Internet: ):

public class Cache{
  static Map<String,Object> map = new HashMap<String,Object>();
  static ReentrantReadWriteLock  rwl = new ReentrantReadWriteLock();
  static Lock rLock = rwl.readLock();
  static Lock wLock = rwl.writeLock();

  //获取一个key对应的value
  public static final Object get(String key){
     r.lock();
     try{
         return map.get(key);
     }finally{
         r.unlock();
     }
  }

  //设置key对应的value并返回旧的value
  public static fianl Object put(String key,Object value){
     w.lock();
     try{
        return map.put(key,value);
     }final{
        w.unlock();
     }
  }

  //清空缓存
  public static fianl void clear(){
     w.lock();
     try{
        map.clear();
     } finally{
        w.unlock();
     }
  }
}复制代码


  • Read-write lock lock downgrade

Lock downgrade downgrade means the write lock to be read locks. Process if the current thread holds a write lock, then release it again to acquire a read lock can not be called lock demotion. Lock downgrade means that at the time of holding the write lock reacquisition read lock, get into the process of writing after the release of the lock before the read lock called lock release.

(Derived from the blog.csdn.net/qq_38737992…program: )

public void work() {
        reentrantReadWriteLock.readLock().lock();
 
        if (!update) {
            reentrantReadWriteLock.readLock().unlock();
 
            // 锁降级开始
            reentrantReadWriteLock.writeLock().lock();
            try {
                if (!update) {
                    // 准备数据
                    ++index;
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    update = true;
                }
                reentrantReadWriteLock.readLock().lock();
            } finally {
                reentrantReadWriteLock.writeLock().unlock();
                // 锁降级结束,降级为读锁
            }
        }
        try {
            // 使用数据
            for (int i=0; i<5; i++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":" + index);
            }
        } finally {
            reentrantReadWriteLock.readLock().unlock();
        }
    }
复制代码


Three, synchronized and Lock difference

1, synchronized and Lock difference

synchronized keyword, which is the interface Lock

synchronized state can not determine whether or not to acquire the lock, Lock can determine whether to acquire a lock

synchronized automatically release the lock (a synchronization code after executing the thread will automatically release the lock, the lock release exception occurs during the execution of the thread b)

the need to manually lock finally release the lock (unlock () method releases the lock), or likely to cause thread deadlock.

Two synchronized keyword thread 1 and thread 2, 1 if the current thread to acquire the lock, thread 2 wait, if the blocked thread 1, thread 2 will wait forever.

The lock lock will not necessarily wait any longer, get less than if you try to lock, the thread may not have been waiting is over.


synchronized lock reentrant, can not be interrupted, unfair .

lock lock reentrant, interruptible, be fair

lock lock for a lot of synchronization code synchronization , the synchronized lock for code that a small amount of synchronization problems


Non-reentrant lock: spin lock, wait (), notify (), notifyAll ()

Non-reentrant lock that can not be called recursively, a recursive call deadlock ensues


2, reentrantlock and synchronized difference

reentrantLock have the same synchronized concurrency and memory semantics, in addition to multi-column locks vote, time lock interruption waiting and waiting

Use synchronized locks, A does not release, B will wait forever

Use reentrantlock lock, A does not release, B will wait for some time interrupt latency, and do other things.


synchronized in the JVM level implemented on, not only can monitor the synchronized lock, but an exception when code is executed, JVM release which will come through a number of locking monitoring tools. But not Lock

In the resource competition is not very intense situation, synchronized performance is better than reentrantlock lock , and the competitive situation, the performance of the synchronized fall a few times, and to maintain normal performance reentrantlock.


  • Performance Analysis

synchronized will repeatedly spin to get the lock , waiting in this process thread will not be suspended , thus saving overhead suspend and wake-up context switching

And ReentrantLock , not spin, but directly hang

Thus in the case of small amount of concurrent threads, synchronized because they have a spin lock, lock and lightweight lock biased reasons, do not wait for the thread to hang biased locking even without spin, so in this case than reenttrantlock efficient.


synchronized unfair lock by default; reentrantlock non-default fair locks.


  • Binding multiple conditions

A Reentrantlock object can simultaneously bind multiple Condition objects,

In synchronized, the lock of the object wait(), and notify()or notifyAll()methods may be implemented in a hidden condition.

If you want to add an association and more than one time, the synchronized had to add an extra lock, and Reentrantlock there is no need to do so only need to call multiple new Condition()methods can be.


Guess you like

Origin juejin.im/post/5db943fd51882564635002c2