Read Write Lock
The write is mutually exclusive, the read is shared, and the write and read cannot occur at the same time.
Applicable environment
A scenario that resembles a cache update.
Sample Example
Cache, read more and write more, LRU obsolete.
Read/write Lock
Read, write, and write mutually exclusive.
package readwritelock;public class readwritelock {private int waitwriters=0; private int writingwriters=0;private int readers=0;//read and write are waiting, write priority, read more threads, write fewer threads, prevent the write thread from being starved to private boolean writefirst=true;public synchronized void readlock () throws Interruptedexception{while (writingwriters>0| | (writefirst&&waitwriters>0)) {Wait ();} Readers++;showdetail (Thread.CurrentThread (). GetName () + "--" + "Readlock");} Public synchronized void readunlock () {Readers--;writefirst=true;showdetail (Thread.currentThread (). GetName () + "--" + "Readunlock"); Notifyall ();} Public synchronized void writelock () throws interruptedexception{waitwriters++;try{// No more writing in the process of reading and writing, waiting while (readers>0| | writingwriters>0) {wait ();}} finally{waitwriters--;} Writingwriters++;showdetail (Thread.CurrentThread (). GetName () + "--" + "Writelock");} Public synchronized void writeunlock () {//release write lock writingwriters--;//wrote,While waiting for the read, write in, read first. Avoid continuous write, read thread hunger Writefirst=false;showdetail (Thread.CurrentThread (). GetName () + "--" + "Writeunlock"); Notifyall (); Private void showdetail (string msg) {System.out.println (Thread.CurrentThread (). GetName () + "--" + "- -------------------------"); System.out.println (Thread.CurrentThread (). GetName () + "--" +msg); System.out.println (Thread.CurrentThread (). GetName () + "--" + "Wait:" +waitwriters); System.out.println (Thread.CurrentThread (). GetName () + "--" + "writing:" +writingwriters); System.out.println (Thread.CurrentThread (). GetName () + "--" + "read:" +readers); System.out.println (Thread.CurrentThread (). GetName () + "--" + "--------------------------");}}
Cache
Based on LINKEDHASHMAP implementation
package readwritelock;import java.util.linkedhashmap;import java.util.map;import java.util.map.entry;public class sharedbuffer<k,v> {private readwritelock lock= New readwritelock ();p rivate linkedhashmap<k,v> buf=null;private final int Size;public sharedbuffer (final int initsize) {this.size= (int) math.ceil (initsize / 0.75f) + 1;this.buf=new LinkedHashMap<K,V> (size, 0.75f, true) { private static final long serialversionuid = -2347727619006196448l;@ Overrideprotected boolean removeeldestentry (entry<k,v> eldest) {boolean Isremove=size () > initsize;if (isremove) {System.out.println (Thread.CurrentThread (). GetName () + "--" + Eldest.getkey () + ":" +eldest.getvalue () + " Discarded! ");} return isremove; } };} Public void put (k k,v v) {try {lock.writelock (); System.out.println (Thread.CurrentThread (). GetName () + "--" + "Buffer after write lock"); System.out.println (Thread.CurrentThread (). GetName () + "--" +this.showsnaphost ()); catch (interruptedexception e) {}try{this.buf.put (K,&NBSP;V); System.out.println (Thread.CurrentThread (). GetName () + "--" + "buffer " +k+ "--+v);} Finally{system.out.println (Thread.CurrentThread (). GetName () + "--" +this.showsnaphost ()); Lock.writeunlock (); System.out.println (Thread.CurrentThread (). GetName () + "--" + "Buffer after write unlock");} Public v get (k k) {try {system.out.println (Thread.CurrentThread (). GetName () + "--" + "buffer before read lock "); Lock.readlock (); System.out.println (Thread.CurrentThread (). GetName () + "--" + "Buffer after&nbsP;read lock ");} catch (Interruptedexception e) {}try {return this.buf.get (k);} Finally{system.out.println (Thread.CurrentThread (). GetName () + "--" +this.showsnaphost ()); Lock.readunlock (); System.out.println (Thread.CurrentThread (). GetName () + "--" + "Buffer read unlock");} Private string showsnaphost () {map<k,v> copy = new linkedhashmap<k ,v> (THIS.BUF); Stringbuilder sb = new stringbuilder ();for (map.entry<k,v> entry : copy.entryset ()) {sb.append (String.Format ("%s:%s ", entry.getkey (), entry.getValue () ));} Return sb.tostring (); }}
Readers
Package Readwritelock;import Java.util.random;public class Reader implements Runnable{private final sharedbuffer< String,string> buf;private Final String myname;public Reader (String myname,sharedbuffer<string,string> buf) { This.myname=myname;this.buf=buf;} @Overridepublic void Run () {random r=new random (); while (true) {String k=integer.tostring (R.nextint (10)); System.out.println (Thread.CurrentThread (). GetName () + "--" +k+ "readed!!! "+this.myname+": "+buf.get (k)"), try {thread.sleep (10);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Written by
Package Readwritelock;import Java.util.random;public class Writer implements Runnable{private final sharedbuffer< String,string> buf;private Final String myname;public Writer (String myname,sharedbuffer<string,string> buf) { This.myname=myname;this.buf=buf;} @Overridepublic void Run () {random r=new random (); int Cnt=0;while (true) {cnt++; String k=null;if (cnt<=10) {k=integer.tostring (R.nextint (10));} Else{k=integer.tostring (R.nextint (100));} Buf.put (k, "" +cnt); System.out.println (Thread.CurrentThread (). GetName () + "--" +k+ "writed!! "+this.myname+": "+cnt"; try {thread.sleep (100);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Test class
Package Readwritelock;public class Test {public static void main (string[] args) {System.out.println ("++++++++++++++++++ ++++++++++++++++++"); Sharedbuffer<string,string> buf=new sharedbuffer<string,string> (10); Reader R1=new Reader ("R1", buf); Reader R2=new Reader ("R2", buf); Writer W1=new writer ("W1", buf); Writer W2=new writer ("W2", buf); Thread rtd1=new thread (r1); Thread rtd2=new thread (R2); Thread Wtd1=new thread (W1); Thread Wtd2=new thread (w2); Wtd1.start (); Wtd2.start (); try {thread.sleep (n);} catch (Interruptedexception E1) { E1.printstacktrace ();} Rtd1.start (); Rtd2.start (); try {rtd1.join (); Rtd2.join (); Wtd1.join (); Wtd2.join ();} catch (Interruptedexception e) { E.printstacktrace ();}}}
This article is from the Java Technology Stack notes blog, so be sure to keep this source http://stroll.blog.51cto.com/11038467/1857276
Java multithreaded (eight) mode-read Write Lock