About synchronize and lock the difference

References: https://www.cnblogs.com/cloudblogs/p/6440160.html

A, synchronize different modified code is locked What?
We all know that synchronize attributes can be modified, code blocks, methods, classes, but modified content different code lock is different.
1, modified non-static properties and methods of the time, got the call this method or property of an object (this) lock .
2, synchronize () when the modified block, get the specified lock object .
3, a modified type, a static method, a static code block , since this pointer is not, therefore to get the class locks, which is the object of the class class .
! ! ! Note: An object has only one lock
 
Second, with regard synchronize
Since synchronize JVM is achieved, thus locking the code when an abnormality occurs, the lock can be released by the JVM objects, comprising the following three cases:
1, the lock thread execution possession over the code block, then release the possession of the lock;
2, possession of a lock thread exception occurs, then JVM will automatically thread releases the lock;
3, possession of a lock thread calls the wait () method to enter the WAITING state needs to release the lock.
 
Third, on the Lock

 

 Due Lock is JDK implementation, so acquiring and releasing Unlike synchronize lock is controlled by the JVM, Lock acquisition and need to manually release, but it is precisely because this was more flexible.

1, lock () acquires the lock and release the lock 

. 1 Lock Lock = ...; Lock.lock ();
 2  the try {    
 . 3     // processing tasks 
. 4 } the catch (Exception EX) {
 . 5 } the finally {
 . 6       lock.unlock ();    // release lock 
7 }

 

2, tryLock () returns a value acquiring a lock can know whether the operation is successful acquire the lock 

. 1 Lock Lock = ...; 
 2  IF (lock.tryLock ()) {
 . 3        the try { 
 . 4           // processing task      
. 5     } the catch (Exception EX) {
 . 6       } the finally {
 . 7            lock.unlock ();    // release lock       
8    }  
 . 9 } the else {   
 10    // If the lock can not be acquired, directly to do other things 
11 }

If the acquisition is successful return True, if the lock is occupied by another thread returns FALSE , the method will return results immediately , will not let the thread has been in a wait state .

 

3, tryLock (long time, TimeUnit unit) and tryLock () is similar, but with different results tryLock returns immediately, the method waits for time period in the case of the lock get next time, if for a limited time or to get the lock returns FALSE, the beginning or if a wait time to get a lock and returns TRUE.

 

4、lockInterruptibly() 

When trying to get lock This way, if the thread is waiting to acquire the lock, the thread can respond Thread.interrupt () interrupted. For not synchronize threads waiting to acquire the lock in the state can not respond to interrupts.

1 public void method() throws InterruptedException {     
2     lock.lockInterruptibly();    
3     try {        //.....     }     
4     finally { lock.unlock(); }   
5 }

lockInterruptibly method must be placed outside the try block or method call statements lockInterruptibly throw InterruptedException, we recommended to use the latter.

 

5、readWriteLock()

The lock to enhance the efficiency of read operations, but to note is that if there is a thread already occupied read lock, other threads at this time if you want to apply for a write lock, the write lock thread application will wait to release the read lock. If there is a thread already occupied write lock, then other threads at this time if the application write lock or read lock, the application threads will have to wait to release the write lock.

 

Four, Lock and synchronized selection:
1, Lock is an interface that belongs to achieve JDK level; and synchronized belongs to the Java language features, in fact, the existing JVM to control (the code is finished, abnormal, JVM will automatically release the lock when the wait).
2, synchronized when an exception occurs, it will automatically release the lock out, so the deadlock now (at this time of deadlock caused by the general logic of the code) does not occur; and Lock must take the initiative in finally unlock the lock, otherwise there will be dead lock.
3, Lock can respond to interrupt thread to wait for the state to stop waiting; but not synchronized.
4. Lock can know whether the thread by successfully obtained a lock, but not synchronized.
5, Lock improves the efficiency of multithreaded read operations.
 
Fifth, expand
1, reentrant lock: the synchronized and locked ReentrantLock are reentrant. When a thread to execute a synchronized method, method1 for example, while in the method1 calls method2 another synchronized method, the thread at this time do not have to apply for re-lock, but the method can be performed directly method2.
 
2, interruptible lock: whether to wait to obtain a lock waiting process can be interrupted. By the above example, we can learn Lock is interruptible lock, but not synchronized.
 
3, fair locks: as far as possible in the order request to acquire the lock, the same multiple threads wait for a lock, when the lock is released, wait the longest thread (first thread request) will get the lock. non-synchronized fair locks, and ReentReadWriteLock ReentrantLock non-default fair lock case, but may be provided to lock fair.
ReentrantLock lock = new ReentrantLock(true);
ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
Lock that is set to TRUE fair, no parameter is FALSE or non-fair lock.
 
4, read-write locks: read and write access to critical resource lock will be divided into two locks, a read lock and a write lock. Increase the flexibility of reading and writing. That ReadWriteLock interface and its implementation ReentrantReadWriteLock.

Guess you like

Origin www.cnblogs.com/simpleDi/p/11517552.html