Java concurrent database -- lock, java concurrency --

Source: Internet
Author: User

Java concurrent database -- lock, java concurrency --

  • Synchronized defects:

Modified by synchronized. When a thread acquires the corresponding lock and executes the code block, other threads can only wait until the lock is acquired to release the lock, when the acquiring thread is blocked and the lock is not released, the waiting thread will wait for a long time. In addition, when multiple threads only perform read operations, there is no conflict between threads. You can do this by using Lock. The Lock also knows whether the thread has successfully obtained the Lock.

  • Comparison between Lock and synchronized

1) Lock is not built into the Java language, and synchronized is a keyword of the Java language, so it is a built-in feature. Lock is a class that enables synchronous access;

2) the Lock and synchronized are a little different. Using synchronized does not require you to manually release the Lock. After the synchronized method or synchronized code block is executed, the system will automatically let the thread release the Lock occupation, and the Lock must be manually released by the user. If the Lock is not released, it may lead to a deadlock.

  • Common classes in the java. util. concurrent. locks package

1) Lock

  Source code of the lock Interface

1 public interface Lock {2     void lock();3     void lockInterruptibly() throws InterruptedException;4     boolean tryLock();5     boolean tryLock(long time, TimeUnit unit) throws         InterruptedException;6     void unlock();7     Condition newCondition();8 }

For details about the method, see API.

  2) ReentrantLock

  A reentrant mutex lockLock, It has and usessynchronizedThe method and the implicit monitor lock accessed by the statement have the same basic behavior and semantics, but are more powerful.

Instance:

 1 public class LockTest { 2     public static void main(String[] args) { 3         final Output output = new Output(); 4         while(true){ 5             new Thread(new Runnable() { 6                 @Override 7                 public void run() { 8                     output.output("love"); 9                 }10             }).start();11             new Thread(new Runnable() {12                 @Override13                 public void run() {14                     output.output("hate");15                 }16             }).start();17         }18         19     }20     21 }    22 class Output{23     Lock lock = new ReentrantLock();24     public void output(String str){25         lock.lock();26         try {27             for (int i = 0; i < str.length(); i++) {28                 System.out.print(str.charAt(i));29             }30             System.out.println();31         } catch (Exception e) {32             e.printStackTrace();33         } finally{34             lock.unlock();35         }36         37         38     }39 }

 3) ReadWriteLock

  The source code of the ReadWriteLock interface. It only provides the method for obtaining the write lock and read lock.

 1 public interface ReadWriteLock { 2     /** 3      * Returns the lock used for reading. 4      * 5      * @return the lock used for reading. 6      */ 7     Lock readLock(); 8   9     /**10      * Returns the lock used for writing.11      *12      * @return the lock used for writing.13      */14     Lock writeLock();15 }

One is used to obtain the read lock and the other is used to obtain the write lock. That is to say, the file read/write operations are separated and divided into two locks to be allocated to the thread, so that multiple threads can perform read operations simultaneously.

  4) ReentrantReadWriteLock

  Several attributes of the ReentrantReadWriteLock class:

  • Order:This class does not prioritize the reads or writes to the sort of lock access. However, it does support optionalFairnessPolicy.
  • Re-import:This lock allows reader and writer to followReentrantLockTo obtain the read lock or write lock again. Only when all the write locks maintained by the write thread have been released can the reader re-use them. In addition, writer can obtain the read lock, but in turn it is not true. In other applications, re-entry is useful when the write lock is maintained during the calling or callback of the read/write operations in the read/write status. If reader attempts to obtain the write lock, it will never succeed.
  • Lock downgrade:Re-entry also allows you to downgrade from the write lock to the read lock. The implementation method is to first obtain the write lock, then obtain the read lock, and finally release the write lock. However, it is impossible to upgrade the read lock to the write lock.
  • Lock interruption:Both read locks and write locks support Interruption During lock acquisition.

  Example: use three threads to read and write data respectively.

1 public class ReadWriteLockTest {2 public static void main (String [] args) {3 final Date date = new Date (); 4 for (int I = 0; I <3; I ++) {5 new Thread (new Runnable () {6 @ Override 7 public void run () {8 while (true) {9 date. put (); 10} 11} 12 }). start (); 13 new Thread (new Runnable () {14 15 @ Override16 public void run () {17 while (true) {18 date. get (); 19} 20} 21 }). start (); 22} 23 24} 25} 26 27 class Date {28 29 ReadWriteLock rwl = new ReentrantReadWriteLock (); 30 31 private Integer date; 32 33 public void get () {34 rwl. readLock (). lock (); 35 try {36 System. out. println (Thread. currentThread (). getName () + "prepare to read data"); 37 System. out. println (Thread. currentThread (). getName () + "read data:" + date); 38} catch (Exception e) {39 // TODO: handle exception40} finally {41 rwl. readLock (). unlock (); 42} 43 44} 45 46 public void put () {47 rwl. writeLock (). lock (); 48 try {49 System. out. println (Thread. currentThread (). getName () + "prepare to write data"); 50 Thread. sleep (50); 51 date = new Random (). nextInt (5000); 52 System. out. println (Thread. currentThread (). getName () + "write data:" + date); 53} catch (Exception e) {54 // TODO: handle exception55} finally {56 rwl. writeLock (). unlock (); 57} 58} 59}

In this way, reading, reading, and writing greatly improve the efficiency of read operations.

5) Selection of Lock and synchronized

To sum up, Lock and synchronized are different in the following aspects:

1) Lock is an interface, while synchronized is a keyword in Java, and synchronized is a built-in language implementation;

2) synchronized will automatically release the Lock occupied by the thread in case of an exception, so it will not cause a deadlock. In case of an exception, if the Lock does not actively pass unLock () to release the Lock, it is likely to cause a deadlock. Therefore, you must release the Lock in the finally block when using the Lock;

3) Lock can interrupt the response of the thread waiting for the Lock, but synchronized does not work. When synchronized is used, the waiting thread will keep waiting and cannot respond to the interruption;

4) You can use Lock to know whether the Lock is successfully obtained, but synchronized cannot.

5) Lock can improve the reading efficiency of multiple threads.

In terms of performance, if the competition resources are not fierce, the performance of the two is similar, and when the competition resources are very fierce (that is, there are a large number of threads competing at the same time ), in this case, the Lock performance is far better than synchronized. Therefore, you must select an appropriate option for specific use.

  • Introduction to lock-related concepts

  1) reentrant lock

  If the lock is reentrant, it is called a reentrant lock. For example, synchronized and ReentrantLock are both reentrant locks. In my opinion, they actually indicate the lock allocation mechanism: thread-based allocation rather than method-based allocation. For example, when a thread executes a synchronized method, such as method1, and method1 calls another synchronized Method method2, the thread does not have to apply for a lock again, instead, you can directly execute the method method2.

1 class MyClass {2     public synchronized void method1() {3         method2();4     }5     public synchronized void method2() {6          7     }8 }

The two methods method1 and method2 in the above Code are modified with synchronized. If thread A executes method1 at A certain time point, thread A obtains the Lock of this object, because method2 is also the synchronized method, if synchronized is not reentrant, thread A needs to apply for A lock again. But this will cause A problem, because thread A already holds the Lock of this object, and is applying to obtain the Lock of this object, in this way, thread A waits for the lock that will never be obtained. Because both synchronized and Lock are reentrant, the above phenomenon will not occur.

  2) locks that can be interrupted

  Locks that can respond to interruptions, as the name implies.

In Java, synchronized is not an interruption Lock, but a Lock is an interruption Lock.

If thread A is executing the lock code and thread B is waiting to obtain the lock, thread B may not want to wait because the wait time is too long and want to handle other tasks first, we can let it interrupt itself or interrupt it in other threads. This is the locks that can be interrupted.

The lockInterruptibly () usage has been demonstrated in the previous section, which reflects the tolerance of Lock.

  3) fair lock

  Fair locks are obtained in the order of request locks. For example, multiple threads are waiting for a lock. When the lock is released, the thread with the longest wait time (the thread with the first request) will obtain the lock. This is the fair lock.

Unfair locks cannot guarantee that the locks are obtained in the order of request locks. This may cause some or some threads to never get the lock.

In Java, synchronized is an unfair lock, which cannot guarantee the order in which the waiting thread obtains the lock.

For ReentrantLock and ReentrantReadWriteLock, it is a non-fair lock by default, but can be set as a fair lock.

4) read/write lock

  The read/write lock divides access to a resource (such as a file) into two locks, one read lock and one write lock.

Because of the read/write lock, the read operations between multiple threads do not conflict.

ReadWriteLock is the read/write lock, which is an interface that is implemented by ReentrantReadWriteLock.

Read locks can be obtained through readLock () and write locks can be obtained through writeLock.

The cache generally involves reading and writing, so you can apply the lock to implement the cache system. The core code of the cache system is as follows:

1 public class CacheDemo {2 3 private Map <String, Object> map = new HashMap <String, Object> (); // cache map 4 private ReadWriteLock rwl = new ReentrantReadWriteLock (); 5 private ReadLock readLock = (ReadLock) rwl. readLock (); // read lock 6 private WriteLock writeLock = (WriteLock) rwl. writeLock (); // write lock 7 8 public Object getValue (String key) {9 readLock. lock (); 10 Object value = null; 11 try {12 value = map. get (key); 13 if (value = null) {// if the object is empty, the read lock releases 14 readLock. unlock (); 15 writeLock. lock (); // get the write lock to ensure synchronization of 16 try {17 if (value = null) {// judge whether the object is null again to prevent repeated write operations by multi-thread access, 18 value = "abcd"; // get cached data 19} 20 map. put (key, value); 21} catch (Exception e) {22 // TODO: handle exception23} finally {24/** 25 * downgrade the write lock to read lock 26 */27 readLock. lock (); 28 writeLock. unlock (); 29} 30} 31} catch (Exception e) {32 // TODO: handle exception33} finally {34 readLock. unlock (); 35} 36 37 return value; 38} 39}

References:

Http://www.cnblogs.com/dolphin0520/p/3923167.html

JavaAPI

 

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.