Java Multithreading Basics Summary viii.: Reentrantreadwritelock

Source: Internet
Author: User
Tags diff final thread

When it comes to Reentrantreadwritelock, the first thing to do is to draw a reentrantlock. It and the latter are individually implemented and have no inherited or implemented relationships with one another. Then there is the feature of the lock mechanism:

(a). The Writelock can get readlock, but in turn Readlock want to get Writelock never think about it.

(b). The writelock can be demoted to readlock, in the order that the Writelock is obtained Readlock first, then the Writelock is released, and the thread will hold the Readlock. Conversely Readlock want to upgrade to Writelock is impossible, why? Refer to (a), hehe.

(c). Readlock can be held by multiple threads and repel any writelock while acting, while Writelock is a complete mutex. This feature is most important because of the relatively low write data structure for high read frequencies, the use of this type of lock synchronization mechanism can increase the amount of concurrency.

(d). Both Readlock and Writelock support interrupt, semantics are consistent with Reentrantlock.

(e). Writelock supports condition and is consistent with reentrantlock semantics, while readlock cannot use condition or throw unsupportedoperationexception exceptions.

The above is more important, or to measure the use of reentrantreadwritelock basis. Here's a little example to illustrate some of the things:

Java code

Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* @author: Yanxuxin
* @date: 2010-1-7
*/
public class Reentrantreadwritelocksample {

public static void Main (string[] args) {
Testreadlock ();
Testwritelock ();
}

public static void Testreadlock () {
Final Readwritelocksamplesupport support = new Readwritelocksamplesupport ();
Support.initcache ();

Runnable Runnable = new Runnable () {
public void Run () {
Support.get ("test");
}
};

New Thread (runnable). Start ();
New Thread (runnable). Start ();

New Thread (New Runnable () {
public void Run () {
Support.put ("Test", "test");
}
). Start ();
}

public static void Testwritelock () {
Final Readwritelocksamplesupport support = new Readwritelocksamplesupport ();
Support.initcache ();

New Thread (New Runnable () {
public void Run () {
Support.put ("Key1", "value1");
}
). Start ();

New Thread (New Runnable () {
public void Run () {
Support.put ("Key2", "value2");
}
). Start ();

New Thread (New Runnable () {
public void Run () {
Support.get ("Key1");
}
). Start ();
}
}

Class Readwritelocksamplesupport {
Private final Reentrantreadwritelock lock = new Reentrantreadwritelock ();
Private final Lock Readlock = Lock.readlock ();
Private final Lock Writelock = Lock.writelock ();

Private volatile Boolean completed;
Private map<string,string> Cache;

public void Initcache () {
Readlock.lock ();
if (!completed) {
Must release read lock before acquiring write lock
Readlock.unlock (); (1)
Writelock.lock (); (2)
if (!completed) {
cache = new Hashmap<string,string> (32);
Completed = true;
}
Downgrade by acquiring read lock before releasing write lock
Readlock.lock (); (3)
Writelock.unlock (); (4) Unlock write, still hold read
}

System.out.println ("Empty?" + cache.isempty ());
Readlock.unlock ();
}

public string get (string key) {
Readlock.lock ();
System.out.println (Thread.CurrentThread (). GetName () + "read.");
Startthecountdown ();
try{
return Cache.get (key);
}
finally{
Readlock.unlock ();
}
}

public string put (string key, String value) {
Writelock.lock ();
System.out.println (Thread.CurrentThread (). GetName () + "write.");
Startthecountdown ();
try{
Return Cache.put (key, value);
}
finally {
Writelock.unlock ();
}
}

/**
* A Simple countdown,it'll stop after about 5s.
*/
public void Startthecountdown () {
Long currenttime = System.currenttimemillis ();
for (;;) {
Long diff = System.currenttimemillis ()-currenttime;
if (diff > 5000) {
Break
}
}
}
}

This example modifies the example provided by the JDK API, where the Readwritelocksamplesupport auxiliary class is responsible for maintaining a map, assuming that most of the map's multithreading is read, and that only a small proportion is multi-threaded competition to modify the value of the map. The Initcache () is a simple description of the characteristics (a), (b). If the code in the annotation (1) and (2) is exchanged in this method, it will find an easy deadlock, of course, because of the function of the feature (1). The position of the Code at (3), (4) again proves the attribute (a) and strongly reflects the feature (b)--writelock degraded to readlock after the cache initialization was completed. In addition get (), the put () method will spend nearly 5s of time in the method after acquiring the lock on the thread.

The two static test methods in Reentrantreadwritelocksample test the repulsion of Readlock and Writelock respectively. In Testreadlock (), open three threads, the first two trying to get Readlock and the latter to get writelock. The results of the execution can be seen: the print results in the Readwritelocksamplesupport get () method appear almost simultaneously in the first two threads, while the print results in put () are nearly 5s. This explains that Readlock can hold and repel Writelock's holding threads in multiple threads. Testwritelock (), also opens three threads. The first two are going to get writelock, and the last one gets readlock. The result is three print results have nearly 5s interval, which shows that Writelock is exclusive, more alone!

The summary of this article reentrantreadwritelock a bit late, mainly to JS and Ajax is very interested, and suddenly feel that CSS is also very fun. Looking at the Internet, a lot of people are crazy about technology and personal planning, I think for me: not infatuated with technology but as an interest, whether it is Java-ee or the front end of the web, whether it is the mobile device of the tripartite development or professional video editing technology, I would like to be naturally interested in, conditional on go mercilessly play. I think I'm obsessed with only high-performance computers and the Internet, haha.

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.