Multi-thread using read-write lock Reentrantreadwritelock to implement cache system

Source: Internet
Author: User

Simply cache the system: when the thread is fetching data, if that data exists in my memory, I return the data, and if it doesn't exist in my cache system, then go to the database and return the data and save it in my cache.

This involves reading and writing issues: When multiple threads are performing read operations (both read-lock), if there is data return, if there is no data, then the first read the thread to get the data, and then write operations, the first thread needs to release the read lock and then write the lock. After the first write, read the lock at home, other threads use the judgment, if there is the data, in the direct past read without the write lock.

Examples of caching on the API are as follows:

Class Cacheddata {   Object data;   Volatile Boolean cachevalid;   Reentrantreadwritelock rwl = new Reentrantreadwritelock ();   void Processcacheddata () {     rwl.readlock (). Lock ();     if (!cachevalid) {        //must release read lock before acquiring write lock        rwl.readlock (). Unlock ();        Rwl.writelock (). Lock ();        Recheck state because another thread might has acquired        //   write lock and changed state before we did.        if (!cachevalid) {          data = ...          Cachevalid = true;        }        Downgrade by acquiring read lock before releasing write lock        Rwl.readlock (). Lock ();        Rwl.writelock (). Unlock (); Unlock write, still hold read     } use     (data);     Rwl.readlock (). Unlock ();   } }


Reentrantreadwritelock

This class has the following properties:

  • Get Order

    This class does not prioritize reader precedence or writer precedence to lock-access ordering. However, it does support an optional fairness policy.

    Non-fair mode (default)
    When an unfair (default) construct is not specified, the order in which the read and write locks are entered is restricted by the reentrancy constraint. A continuously competing unfair lock may defer one or more reader or writer threads indefinitely, but throughput is usually higher than a fair lock.

    Fair mode
    When a thread is constructed fairly, the thread competes for entry with a strategy that approximates the order of arrival. When you release a lock that is currently held, you can assign a write lock to a single writer thread that waits the longest, and if there is a reader thread with a set of wait times that is larger than all the waiting writer threads, a write lock is assigned to that group.

    If the write lock is persisted, or if there is a waiting writer thread, the thread attempting to obtain a fair read lock (non-reentrant) will block. The thread will not get a read lock until the current oldest waiting writer thread has obtained and freed the write lock. Of course, if you wait for the writer to abandon its wait while leaving one or more reader threads to be the longest waiter in the queue with the write lock free, the reader will be assigned a read lock.

    Threads that attempt to obtain a fair write lock (non-reentrant) will block unless both the read lock and the write lock are free (which means there is no waiting thread). (Note that non-blocking ReentrantReadWriteLock.ReadLock.tryLock() and ReentrantReadWriteLock.WriteLock.tryLock() methods do not adhere to this fair setting and will acquire the lock (if possible), regardless of the waiting thread).

  • Re-entry

    This lock allows both reader and writer ReentrantLock to regain read or write locks in the style they follow. After all write locks held by the write thread have been freed, the re-entry reader is allowed to use them.

    In addition, writer can obtain a read lock, but the reverse is not true. In other applications, a re-entry is useful when a write lock is persisted during a call or callback to a method that performs a read operation in a read-lock state. If reader attempts to acquire a write lock, it will never succeed.

  • Lock downgrade

    The re-entry also allows the downgrade from a write lock to a read lock, which is achieved by acquiring a write lock, then acquiring a read lock, and finally releasing the write lock. However, it is not possible to upgrade from a read lock to a write lock.

  • Lock-Acquired interrupts

    Read and write locks support interrupts during lock acquisition.

  • ConditionSupport

    A write lock provides an implementation that behaves the same as the provided implementation does for a Condition write lock ReentrantLock.newCondition() Condition ReentrantLock . Of course, this Condition can only be used for write locks.

    The read lock is not supported Condition and readLock().newCondition() will be thrown UnsupportedOperationException .

  • Monitoring

    This class supports some methods of determining whether to hold a lock or to compete for a lock. These methods are designed to monitor system state rather than synchronization control.


The Java implementation is as follows:

Package Andy.thread.test;import Java.util.hashmap;import Java.util.map;import Java.util.concurrent.locks.readwritelock;import java.util.concurrent.locks.reentrantreadwritelock;/** * @author Zhang,tianyou * @version November 9, 2014 morning 9:29:42 */public class Threadcache {private static map<string, object> Cachema p = new hashmap<string, object> ();p ublic static void Main (string[] args) {for (int i = 0; i <; i++) {New Threa D (New Runnable () {@Overridepublic void Run () {String obj = (string) getData ("Andy"); System.out.println (obj);}}). Start ();}} public static Object GetData (String key) {Readwritelock Rwllock = new Reentrantreadwritelock ();//First read lock Rwllock.readlock () . Lock (); Object value = null;try {value = Cachemap.get (key);//If the cache does not exist if (value = = null) {//If value is null the read lock is freed, the thread acquires a write lock, and Other threads can only wait for the write lock to be released in order to read the lock Rwllock.readlock (). unlock ();//Add Write lock Rwllock.writelock (). Lock (); try {if (value = null) {// Get data from data value = "Andy is Shuai ge";//Query database//cache Cachemap.put (key, value);}} finally {RwlloCk.writelock (). Unlock ();} Rwllock.readlock (). Lock ();}} finally {//releases the read lock Rwllock.readlock () obtained for the first time. Unlock (); return value;}}


The following results are performed:

Andy is Shuai Geandy is Shuai Geandy are Shuai Geandy is Shuai Geandy are Shuai Geandy is Shuai Geandy are Shuai Geandy is sh Uai Geandy is Shuai geandy is Shuai ge


Multi-thread using read-write lock Reentrantreadwritelock to implement cache system

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.