java threads: mutex and read-write locks

Keywords: Java Database Google xml

Links to the original text: https://my.oschina.net/u/580135/blog/612244

Two mutex mechanisms:

1,synchronized

2,ReentrantLock

ReentrantLock is a new feature of jdk5. ReentrantLock can completely replace the traditional synchronized locking mechanism. It is more object-oriented and flexible to adopt ReentrantLock. There are many articles on comparing the two locking modes on the internet. There are not many words here. baidu and google just drop out. In this blog, we also write a classic example of the implementation of these two kinds of locks, Producer and Consumer.

synchronized mode: "java Threads: Three Ways to Realize Producer-Consumer Problem _1"

ReentranLock mode: "java Threads: Three Ways to Realize Producer-Consumer Problem _2"

 

As for read-write locks, language interpretation is better than code interpretation. Here are two examples to illustrate the use of read-write locks and read-write locks:

Example 1:

  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3. import java.util.concurrent.locks.ReadWriteLock;  
  4. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  5.   
  6. /** 
  7.  * @author amber2012 
  8.  *  
  9.  * ReadWriteLock 
  10.  *  
  11.  * In multi-threaded environment, reading and writing the same data will involve thread security. For example, when one thread reads data, another thread reads data in the 
  12.  * Writing data results in inconsistency between the front and back data; when one thread writes data, the other thread writes, which also results in the data that the thread sees before and after. 
  13.  * Inconsistency. 
  14.  *  
  15.  * At this time, mutex can be added to the read-write method. At any time, only one read or write operation of one thread can be allowed, and no read or write operation of other threads can be allowed. 
  16.  * Such a problem can be solved, but the efficiency is greatly discounted. Because in a real business scenario, the number of operations to read data is usually high. 
  17.  * In the operation of writing data, the read-read operation between threads does not involve thread safety. There is no need to add mutex, as long as it is in the read-write, write-write period. 
  18.  * Just lock it in between. 
  19.  *  
  20.  * For this situation, read-write lock is the best solution! 
  21.  *  
  22.  * The mechanism of read-write locks: 
  23.  *      "Read-Read "No Mutual Exclusion" 
  24.  *      "Read-Write Mutual Exclusion 
  25.  *      "Write-Write Mutual Exclusion 
  26.  *  
  27.  * That is to say, at all times it must be guaranteed that: 
  28.  *      Only one thread is writing; 
  29.  *      When the thread is reading, the write operation waits. 
  30.  *      When a thread is writing, the write and read operations of other threads have to wait. 
  31.  *  
  32.  * Here is a cache class for demonstrating the operation of read-write locks: reentry, degradation 
  33.  */  
  34. public class CachedData {  
  35.       
  36.     //Caches should be singletons, which are designed in singleton mode.  
  37.     private static CachedData cachedData = new CachedData();  
  38.     private final ReadWriteLock lock = new ReentrantReadWriteLock();//Read write lock  
  39.     private Map<String, Object> cache = new HashMap<String, Object>();//cache  
  40.       
  41.     private CachedData(){  
  42.     }  
  43.       
  44.     public static CachedData getInstance(){  
  45.         return cachedData;  
  46.     }  
  47.       
  48.     //Read cache:  
  49.     public Object read(String key) {  
  50.         lock.readLock().lock();  
  51.         Object obj = null;  
  52.         try {  
  53.             obj = cache.get(key);  
  54.             if (obj == null) {  
  55.                 lock.readLock().unlock();  
  56.                 //In this case, other threads may acquire locks  
  57.                 lock.writeLock().lock();  
  58.                 try {  
  59.                     if (obj == null) {  
  60.                         obj = "Find the database"//The actual action is to find the database  
  61.                         //Update the data to the cache:  
  62.                         cache.put(key, obj);  
  63.                     }  
  64.                 } finally {  
  65.                     //In the process of acquiring the write lock, the current thread can acquire the read lock, which is called the lock reentry, and then leads to the degradation of the write lock, called the degraded lock.  
  66.                     //Write locks can be degraded by reentrant, but only when all write locks held by the current thread have been released can reentrant reader be allowed to use  
  67.                     //They are. So in the reentrant process, other threads will not have access to locks (the benefits of doing so). Imagine releasing the write lock first.  
  68.                     //What are the disadvantages of reading locks? If you do, you may be interrupted by other threads after releasing the write lock and before getting the read lock.  
  69.                     //Step of reentry - > degraded lock: first get the write lock, then get the read lock, and finally release the write lock (emphasis)  
  70.                     lock.readLock().lock();   
  71.                     lock.writeLock().unlock();  
  72.                 }  
  73.             }  
  74.         } finally {  
  75.             lock.readLock().unlock();  
  76.         }  
  77.         return obj;  
  78.     }  
  79. }  

Example 2:
  1. import java.util.Map;  
  2. import java.util.TreeMap;  
  3. import java.util.concurrent.locks.Lock;  
  4. import java.util.concurrent.locks.ReadWriteLock;  
  5. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  6.   
  7. import javax.xml.crypto.Data;  
  8.   
  9. /** 
  10.  * @author amber2012 
  11.  *  
  12.  * jdk A good example of the use of the ReentrantReadWriteLock class in the document is given below. 
  13.  *  
  14.  * ReentrantReadWriteLock can be used to improve concurrency when using some kinds of Collections. Usually, in anticipation of collection 
  15.  * Very large, reader threads access it more than writer threads, and entail operations cost more than synchronization overhead, which is worth trying. For example, the following 
  16.  * TreeMap is a class that uses TreeMap and is expected to be large and accessible at the same time.   
  17.  */  
  18. public class RWDictionary {  
  19.   
  20.     private final Map<String, Data> map = new TreeMap<String, Data>();  
  21.     private final ReadWriteLock rwl = new ReentrantReadWriteLock();  
  22.     private final Lock readLock = rwl.readLock();  
  23.     private final Lock writeLock = rwl.writeLock();  
  24.   
  25.     public Data get(String key) {  
  26.         readLock.lock();  
  27.         try {  
  28.             return map.get(key);  
  29.         } finally {  
  30.             readLock.unlock();  
  31.         }  
  32.     }  
  33.   
  34.     public String[] allKeys() {  
  35.         readLock.lock();  
  36.         try {  
  37.             return (String[]) map.keySet().toArray();  
  38.         } finally {  
  39.             readLock.unlock();  
  40.         }  
  41.     }  
  42.   
  43.     public Data put(String key, Data value) {  
  44.         writeLock.lock();  
  45.         try {  
  46.             return map.put(key, value);  
  47.         } finally {  
  48.             writeLock.unlock();  
  49.         }  
  50.     }  
  51.   
  52.     public void clear() {  
  53.         writeLock.lock();  
  54.         try {  
  55.             map.clear();  
  56.         } finally {  
  57.             writeLock.unlock();  
  58.         }  
  59.     }  
  60. }  

Reproduced in: https://my.oschina.net/u/580135/blog/612244

Posted by moberemk on Thu, 03 Oct 2019 18:47:40 -0700