[Graphical Java] read/write lock Reentrantreadwritelock

Source: Internet
Author: User

Graphic Reentrantreadwritelock

If you have previously used a read-write lock, you can read this article directly. If it has not been used before, then please cooperate with my other article to see: [Source Analysis] read-write lock Reentrantreadwritelock

0. Demo

I first give a demo, so that everyone can according to the code I gave, debugging side to see the source. Or that sentence: note "My", I renamed the Reentrantreadwritelock class in order to "Myreentrantreadwritelock" class, "Lock" class renamed to "MyLock" class. When everyone pastes my code, the corresponding "my "All removed is good, otherwise it will compile error OH."

The demo is a fair read and write lock.

Import Java.util.hashmap;import java.util.map;import java.util.scanner;import java.util.concurrent.locks.Lock; Import Java.util.function.supplier;public class ReentrantReadWriteLockTest2 {static final Scanner Scanner = new Scanne    R (system.in);    static volatile String cmd = "";    private static Myreentrantreadwritelock lock = new Myreentrantreadwritelock (true);    private static Myreentrantreadwritelock.readlock Readlock = Lock.readlock ();    private static Myreentrantreadwritelock.writelock Writelock = Lock.writelock (); public static void Main (string[] args) {for (map.entry<string, lock> entry:new hashmap<string, lock>                {{for (int i = 0; i < i++) {put ("R" + I, readlock);            Put ("W" + I, writelock);        }}}.entryset ()) {New Thread ((), Func (Entry::getvalue, Entry.getkey ())). Start ();        } while (Scanner.hasnext ()) {cmd = Scanner.nextline ();    }    }public static void Func (Supplier<lock> mylocksupplier, string name) {String en_type = Mylocksupplier.get (). g        Etclass (). Getsimplename (). toLowerCase (). Split ("lock") [0]; String Zn_type = (en_type.equals ("read")?        "read": "Write");        Blockuntilequals ((), CMD, "lock" + En_type + "" + name);        Mylocksupplier.get (). Lock ();        SYSTEM.OUT.PRINTLN (name + "acquired" + Zn_type + "lock");        Blockuntilequals ((), cmd, "unlock" + En_type + "" + name);        Mylocksupplier.get (). Unlock ();    SYSTEM.OUT.PRINTLN (name + "released" + Zn_type + "lock"); } private static void Blockuntilequals (Supplier<string> cmdsupplier, final String expect) {while (!cmdsup    Plier.get (). Equals (expect)) QuietSleep (1000);        } private static void QuietSleep (int mills) {try {thread.sleep (Mills);        } catch (Interruptedexception e) {e.printstacktrace (); }    }}

Use the example below.

We can see that R1 holds a read lock and R2 to apply for a read lock, or it can be successful. Indicates that read locks can be shared.

Next write lock

1. Start diagram (Fair read/write Lock)

After we instantiate a read-write lock, the state of the lock is roughly as follows:

The lock is now idle.

If this time R1 to apply to read the lock. Then you can directly succeed, changing the black shaded part below.

Firstreader is a reference to a thread. Read locks are shared and can have many threads to acquire read locks. The Firstreader is a record of the first thread in the read lock thread that holds a read lock.

Firstreaderholdcount is the number of read lock acquisition (that is, the number of times the Firstreader is re-entered) of the thread referenced by Firstreader

What happens next if R2 to apply for a read lock?

R2 will apply for success and change as follows:

Where Cacheholdcounter is a reference and always points to the last counter that gets the read-lock thread.

Next, let the W1 thread request a write lock. The write lock and the read lock are mutually exclusive, so the write lock cannot be applied successfully, so it enters the ' wait queue '.

Because the wait queue is lazy-initialized, this is the time to generate the head node for the wait queue:

Then the w1 corresponding node end is inserted into the ' Waiting queue ':

Then the waitstatus of the current node's predecessor node is set to-1. 1 indicates that the successor node is active on the waiting thread.

The thread W1 then hangs with confidence:

What happens when we let the R3 thread get a read lock?

(We are now demonstrating a fair lock, if the thread is waiting in the queue, subsequent requests for read-lock threads will not be directly taken to the read lock, but into the waiting queue. After all, write the lock first, you can not queue.)

The thread R3 into the ' waiting queue '. Then the thread R3 hangs. Changes as shown in the black shaded section.

Next we let R4 apply to read the lock, and the end result, like R3, is to enter the "Waiting queue" at the very end. (but this R4 is useful in the following explanation)

So R4 don't have to talk about it, just like R3:

Next we release R1 's Read lock:

Then release the R2 read lock:

(Cachedholdcounter I did not add a shadow, because, he really does not become null, or point to the original element, but this is not important.)

The first thread in the ' Wait queue ' is activated when the thread R2 the read lock and discovers that the read lock has been completely freed.

And let the first thread correspond to node as the new head. Eliminate the original head.

Release the write lock for W1:

After the thread W1 has freed the read lock, it activates its successor R3.

After the R3 is activated, it is ready to acquire a read lock.

After you point the Firstreader to yourself, replace yourself with the new head node:

After the thread R3 requests the read lock, see if the nextwaiter of the successor node equals node.shared. If so, then the successor node will be awakened.

So the next step is to wake up R4:

Now that the R4 was activated, R4 began to apply for reading the lock:

Then R4 is about to become the new head node:

Here, the demo part of the demo is finished.

Finally, let's release R3 and R4 in turn. Anyway, there's not much left.

When the R3 is released, the changes are as follows:

Finally we release the R4:

(The cachedholdcounter is not really null, but it is still pointing to the original element. It's useless here, so there's nothing to say)

After the thread R4 executes, all the threads are freed. The status of the lock is as follows:

Here, the entire fair read and write lock application lock, release the lock process, are all finished.

[Graphical Java] read/write lock Reentrantreadwritelock

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.