Java Concurrency-Lock-reentrantlock (re-entry Lock) and Reentrantreadwritelock (read-write lock)

Source: Internet
Author: User

    • Synchronization control is an essential means of concurrent programs, the Synchronized keyword is a simple control method, in addition, the JDK inside and the package also provides a lock interface, the interface provides the lock () method and Unlock () Method supports explicit and explicit lock-out operations.
Reentrantlock (re-entry Lock)

The re-entry lock can completely replace the Synchronized keyword, and the ability to re-enter the lock in earlier versions of JDK5 is much better than synchronized, but the JDK has done a lot of optimizations in synchronized from JDK6, and the performance gap between the two is small.

 Public classTest { Public StaticReentrantlock lock =NewReentrantlock ();  Public Static inti = 0;  Public Static voidIncrease () {Try{lock.lock (); I++; }finally{lock.unlock (); }    }     Public Static voidMain (string[] args)throwsException {Thread T1=NewTestthread (); Thread T2=NewTestthread ();        T1.start ();        T2.start ();        T1.join ();        T2.join ();    System.out.println (i); }}classTestthreadextendsThread {@Override Public voidrun () { for(intj = 0; J < 1000; J + +) {test.increase (); }    }}

From this code you can see that the re-entry lock has a display of operating procedures compared to synchronized, we need to manually define the verification lock, verify the release lock, but also because of this, the re-entry lock logic control flexibility is better than synchronized.

Fair lock

In most cases, lock applications are unfair. If a thread 1 requests lock a first, and then thread 2 also requests lock A, then when lock A is available, whether thread 1 can acquire a lock or thread 2 is not necessarily, the system simply picks one randomly from the waiting queue of the lock.

The re-entry lock allows us to set the fairness of it. A key feature of fair locking is that it does not produce hunger. Just queue up and you'll finally get the resources. You can create a fair lock using the following constructor:

 Public Reentrantlock (Boolean Fair)

When the parameter fair is true, the lock is fair, of course, due to the fairness of the need to maintain an orderly queue, so fair lock implementation cost is higher, the performance is relatively lower, so the default is a non-fair lock

 Public classTest { Public StaticReentrantlock lock =NewReentrantlock (true);  Public Static voidMain (string[] args)throwsException {Thread T1=NewTestthread (); Thread T2=NewTestthread ();        T1.start ();    T2.start (); }}classTestthreadextendsThread {@Override Public voidrun () { while(true)        Try{Test.lock.lock (); System.out.println (Thread.CurrentThread (). GetName ()+ "Get Lock"); } finally{Test.lock.unlock (); }    }}

You can see that two threads alternately acquire a lock after a fair lock is made on the code

thread-1 Get lock thread-0 Get lock Thread-1 Get lockthread-0 Get lock Thread-1 Get lock thread- 0 Get lock Thread-1 Get lock thread-0 Get lockthread-1 Get lock thread-0 Get lock thread-  1 Get lock thread-0 Get lock Thread-1 Get lock ...

Some other ways to Reentrantlock:

 Public Boolean Trylock (); // with this method, the current thread attempts to acquire a lock, and if the lock is not occupied by another thread, the request for a lock succeeds and returns True, or false immediately. This mode does not cause threads to wait and therefore does not create deadlocks. 

 Public boolean trylock (long  timeout, timeunit unit)// here Trylock receives two parameters, one representing the wait length, A unit that represents a time frame that returns true if a lock is obtained within a certain timeframe, or returns false directly, without continuing to wait for the lock. 
 Public classTestImplementsRunnable { Public StaticReentrantlock lock =NewReentrantlock (); @Override Public voidrun () {Try {            if(Lock.trylock (5, Timeunit.seconds))                {System.out.println (Thread.CurrentThread (). GetName ()); System.out.println ("Get Lock Success"); Thread.Sleep (6000); } Else{System.out.println (Thread.CurrentThread (). GetName ()); System.out.println ("Get Lock Failed"); }        } Catch(interruptedexception e) {e.printstacktrace (); } finally {            if(Lock.isheldbycurrentthread ()) {lock.unlock (); }        }    }     Public Static voidMain (String args[]) {Test Timelock=NewTest (); Thread Thread1=NewThread (Timelock); Thread thread2=NewThread (Timelock);        Thread1.start ();    Thread2.start (); }}

Output Result:

Thread-0Get lock Successthread-1get lock failed

Other:

The specific principle of the re-entry lock and this part of the source code analysis can see this article http://www.cnblogs.com/xrq730/p/4979021.html

Reentrantreadwritelock (read-write lock)

The Readwritelock is a read-write separation lock that JDK5 begins to provide. Read-write split-off effectively helps reduce lock contention to improve system performance. The mechanism of lock separation avoids waiting between multiple read operations threads.

Access constraints for read-write locks:

    • Read-read non-exclusive: No blocking between Read and read
    • Read-write Mutex: Read Jam Write, write also block read
    • Write-Write Mutex: write-write blocking

If the number of operations read in a system is much greater than the write operation, then the read-write lock can play a significant role in improving system performance

 Public classTest {Private StaticLock lock =NewReentrantlock (); Private StaticReentrantreadwritelock Reentrantreadwritelock =NewReentrantreadwritelock (); Private StaticLock Readlock =Reentrantreadwritelock.readlock (); Private StaticLock Writelock =Reentrantreadwritelock.writelock (); Private Static intvalue;  Public StaticObject Handleread (Lock Lock)throwsinterruptedexception {Try{lock.lock (); Thread.Sleep (1000);//Analog Read OperationsSYSTEM.OUT.PRINTLN ("read operation:" +value); returnvalue; } finally{lock.unlock (); }    }     Public Static voidHandlewrite (Lock Lock,intindex)throwsinterruptedexception {Try{lock.lock (); Thread.Sleep (1000);//Analog Write operationsSystem.out.println ("Write operation:" +value); Value=index; } finally{lock.unlock (); }    }     Public Static voidMain (string[] args)throwsException {testreadthread testreadthread=NewTestreadthread (); Testwritethread Testwritethread=NewTestwritethread ();  for(inti = 0; I < 18; i++) {            NewThread (Testreadthread). Start (); }         for(inti = 18; I < 20; i++) {            NewThread (Testwritethread). Start (); }    }        Private Static classTestreadthreadextendsThread {@Override Public voidrun () {Try {                //Test.handleread (lock);Test.handleread (Readlock); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }    Private Static classTestwritethreadextendsThread {@Override Public voidrun () {Try {                //Test.handlewrite (Lock,new Random (). Nextint (+));Test.handlewrite (Writelock,NewRandom (). Nextint (100)); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }}

This piece of code can clearly express the function of the read-write lock, if you do not use read-write lock, then the entire program execution time is about 20s. Swapping read and write locks requires only 2s, where the read thread is completely parallel, saving most of the time.

Java Concurrency-Lock-reentrantlock (re-entry Lock) and Reentrantreadwritelock (read-write lock)

Related Article

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.