One of the most important improvements provided by locks is the Readwritelock interface and its implementation class Reentrantreadwritelock. This class provides two locks, one for read operations and one for write operations. You can have multiple threads performing read operations at the same time, but only one thread can perform a write operation. When a thread is performing a write operation, it is not possible for any thread to perform a read operation.
Public classVisitcounter {PrivateReadwritelock Lock; Private Longcounter; PublicVisitcounter () {counter= 0; Lock=NewReentrantreadwritelock (); } Public Longget () {Longresult =-1; Lock.readlock (). Lock (); Try { //System.out.println (Thread.CurrentThread (). GetName () + "prepare to query the guest counter ..." + "," + New Date ());result =Querycounter (); //System.out.println (Thread.CurrentThread (). GetName () + "Check the guest counter value to" + result + "," + New Date ());}Catch(Exception e) {e.printstacktrace (); } finally{lock.readlock (). Unlock (); } returnresult; } Public voidIncrease () {Lock.writelock (). Lock (); Try { //System.out.println ("New visitors:" + thread.currentthread (). GetName () + "," + New Date ());Updatecounter (); //System.out.println (Thread.CurrentThread (). GetName () + "UPDATE Guest counter complete ..." + "," + New Date ());}Catch(Exception e) {e.printstacktrace (); } finally{lock.writelock (). Unlock (); } } Private LongQuerycounter ()throwsException {thread.sleep (Long) (Math.random () * 10000)); returncounter; } Private voidUpdatecounter ()throwsException {thread.sleep (Long) (Math.random () * 10000)); Counter++; }}
As mentioned earlier, the Reentrantreadwritelock class has two locks, one for the read operation and one for the write operation. The lock used for the read operation is obtained by means of the Readlock () method declared in the Readwritelock interface. This lock is an object that implements the lock interface, so we can use the lock (), Unlock (), and Trylock () methods. The lock used for a write operation is obtained by means of the Writelock () method declared in the Readwritelock interface. This lock is an object that implements the lock interface, so we can use the lock (), Unlock (), and Trylock () methods. It is the programmer's responsibility to ensure that these locks are used correctly and that they are used in the same way as they are designed to be. The value of a variable cannot be modified when a read lock on the lock interface is obtained. Otherwise, there may be errors with inconsistent data.
Java Concurrency-readwritelock & Reentrantreadwritelock