"Java Multithreading" Reentrantreadwritelock__java

Source: Internet
Author: User

1. Define

Readwritelock maintains a pair of related locks, one for read-only operations and another for write operations. As long as there is no writer, the read lock can be persisted by multiple reader threads at the same time. The write lock is exclusive.

2. Applicability

The Readwritelock read operation usually does not change the shared resource, but when a write operation is performed, the lock must be acquired exclusively. For the data structure in which the read operation is most dominant. Readwritelock can provide higher concurrency than exclusive locks. In the case of a read-only data structure, the invariance of the containing is completely unnecessary to consider the lock operation.

It's especially useful for writing less and reading more.

3. Function

Read and write locks also have two locks, one is read operation-related locks, also known as shared locks, the other is write-related locks, also known as exclusive locks.

4. Characteristics

Fairness: Unfair Lock (default), in order to prevent write thread starvation, the rule is: when the waiting queue header node is exclusive mode (that is, to acquire a write lock thread), only get exclusive lock thread can preempt, while the thread attempting to acquire the shared lock must enter the queue blocking When the queue header node is in shared mode (that is, the thread to acquire the read lock), the thread attempting to acquire the exclusive and shared locks can preempt.

Fair locks, using Aqs waiting queues, threads acquire locks in the order of FIFO, so there is no problem with the write thread waiting.

Reentrant: Both read and write locks are reentrant, and the number of reads/writes lock resets is saved in the 32-bit int state's high/low 16-bit. The number of times a single read thread is Threadlocalholdcounter is recorded in the Readholds of the type.

Lock demotion: The write thread acquires a write lock and then releases the write lock, which becomes a read lock from the write lock, which enables the lock to be degraded.

Lock get interrupt: Both read lock and write lock support was interrupted while acquiring lock.

Condition Variable: Write lock provides support for conditional variable (Condition), which is consistent with exclusive lock Reentrantlock, but read lock is not allowed, call Readlock (). Newcondition () Throws a Unsupportedoperationexception exception.

5. Blocking situation

Read and read without blocking,

Read blocking write,

Write blocking read

Write blocking Write

6. Constraints

When any thread holds a write lock or reads a lock, other threads cannot obtain the write lock;

When any thread holds a write lock, other threads cannot acquire the read lock;

Multiple threads can hold read locks at the same time.

7. Examples

Example 1: Read and write more

public class Readwritelocktest {public static void main (string[] args) {Readwritelockdemo RW = new ReadWrite

        Lockdemo (); New Thread (New Runnable () {@Override public void run () {rw.set (int) (Math.rando
            M () * 101));


        }, "Write:". Start (); for (int i = 0; i < i++) {new Thread (new Runnable () {@Override publi
                c void Run () {rw.get ();
        }). Start ();

    class readwritelockdemo{private int number = 0;

    Private Readwritelock lock = new Reentrantreadwritelock (); Read public void Get () {Lock.readlock (). Lock ();//Lock try{System.out.println (Thread.curren
        TThread (). GetName () + ":" + number); }finally{lock.readlock (). unlock ();//Release Lock}}//write public void set (int number) {Lo

 Ck.writelock (). Lock ();       try{System.out.println (Thread.CurrentThread (). GetName ());
        This.number = number;
        }finally{lock.writelock (). Unlock ();
 }
    }
}

Output results:

Write:
Thread-0:
Thread-1:
Thread-2:
Thread-4: Thread-6: Thread-8
:
Thr Ead-9:
Thread-5:
Thread-7:
Thread-3:87

Example 2: Multiple write-read

public class Readwritelock {public static void main (string[] args) {Queue q = new Queue ();
                    for (int i = 0; i < 5, i++) {new Thread () {@Override public void run () {
                    Q.put (New Random (). Nextint (100));

                Q.get ();
        }}.start ();
    Class queue{private Object data = null;
    Private Reentrantreadwritelock RWL = new Reentrantreadwritelock ();
        public void Get () {Rwl.readlock (). Lock ();
            try {System.out.println (Thread.CurrentThread (). GetName () + "ready Read data!");
            Thread.Sleep ((Long) math.random () *1000); System.out.println (Thread.CurrentThread (). GetName () + "have ready read data!"
        +data);
        catch (Interruptedexception e) {e.printstacktrace ();
        }finally {rwl.readlock (). Unlock (); } public void put (Object datas) {Rwl.writelocK (). Lock ();
            try {System.out.println (Thread.CurrentThread (). GetName () + "Ready write read data!");
            Thread.Sleep ((Long) math.random () *1000);
            This.data = datas; System.out.println (Thread.CurrentThread (). GetName () + "have write read data!"
        +data);
        catch (Interruptedexception e) {e.printstacktrace ();
        }finally {rwl.writelock (). Unlock ();
 }
    }
}

Output results:

Thread-2ready Write Read data!
Thread-2have Write read data!98
thread-1ready write read data!
Thread-1have Write read data!7
thread-3ready write read data!
Thread-3have Write read data!38
thread-0ready write read data!
Thread-0have Write read data!64
thread-4ready write read data!
Thread-4have Write read data!64
thread-2ready read data!
Thread-2have Ready Read data!64
thread-0ready read data!
Thread-3ready Read data!
Thread-1ready Read data!
Thread-4ready Read data!
Thread-0have Ready Read data!64
thread-4have ready read data!64
thread-1have ready Read data!64
Thread-3have Ready Read data!64



I talents, if there is a mistake, please also point out
Thank you.

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.