Java Multi-Threading 13: Read and write Locks vs. two synchronization modes

Source: Internet
Author: User

Read-Write Lock Reentrantreadwritelock Overview

A very important piece of content in a large web site is the reading and writing of data, although Reentrantlock has a completely mutually exclusive effect (that is, only one thread is performing the task behind lock at the same time), but it is very inefficient. So a read-write lock Reentrantreadwritelock is provided in the JDK, which can be used to speed up operational efficiency.

Read-write locks represent two locks, one is read-related locks, called shared locks , and the other is write-related locks, called exclusive locks . I understand these two operations as three words:

1, read and read is not mutually exclusive, because the read operation will not thread security issues

2, write and write mutually exclusive, avoid one write operation affect another write operation, raise thread security problem

3, read and write mutual exclusion, avoid read operation when the write operation modified the content, causing thread safety issues

The sum up is that multiple thread can read at the same time, but only one thread is allowed to write at the same time .

Read and read sharing

To prove the first sentence "not mutually exclusive between reading and reading", give a simple example:

Extends reentrantreadwritelock{            voidtry {readlock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "received a read lock, time is" + System.currenttimemillis ()); Thread.Sleep (10000catchfinally {readlock (). Unlock ();        }}}
void Main (string[] args) {    newnewvoidnewnew -Thread (readrunnable); T0.start (); T1.start ();}      

Look at the results of the operation:

thread-0 received a read lock with a read lock time of 1444019668424thread-1 and a time of 1444019668424

Although the method adds a lock, it sleeps for 10 seconds, but two threads still execute the code behind the Lock () method almost simultaneously, to see the time. Description Lock.readlock () Read locks can improve the efficiency of the program, allowing multiple threads to execute the code behind the Lock () method at the same time

Write and Write mutexes

To prove the second sentence "mutual exclusion between writing and writing", a similar proof method:

Extends reentrantreadwritelock{            voidtry {writelock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "obtained a write lock, time is" + System.currenttimemillis ()); Thread.Sleep (10000catchfinally {writelock (). Unlock ();        }}}
void Main (string[] args) {    newnewvoidnewnew -Thread (readrunnable); T0.start (); T1.start ();}      

Look at the results of the operation:

thread-0 obtained a write lock with a time of 1444021393325thread-1 and a write lock of 1444021403325

It can be seen from time that 10000ms is 10s, consistent with the code, proving that reading and reading are mutually exclusive.

Read and write Mutex

Finally prove that the third sentence "between reading and writing mutually exclusive", proving that the method is nothing more than the combination of the above, look at:

PublicClass ThreadDomain48Extendsreentrantreadwritelock{PublicvoidWrite () {Try{Writelock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "Got a write lock, time is" +System.currenttimemillis ()); Thread.Sleep (10000); } catch (Interruptedexception e) {e.printstacktrace ();} finally {writelock (). Unlock ();}} public void Read () { try {readlock (). Lock (); System.out.println (Thread.CurrentThread (). GetName () + "received a read lock, time is" + System.currenttimemillis ()); Thread.Sleep (10000);} Catch (Interruptedexception e) {e.printstacktrace ();} finally {readlock (). Unlock ();              }}} 
PublicStaticvoidMain (string[] args) {final ThreadDomain48 td = new ThreadDomain48 (); Runnable readrunnable = new Runnable () { public void Run () {td.read ();}}; Runnable writerunnable = new Runnable () { public void Run () {td.write ();}}; Thread T0 = new thread (readrunnable); Thread T1 = new thread (writerunnable); T0.start (); T1.start ();}        

Look at the results of the operation:

thread-0 received a read lock with a time of1444021679203thread-1 and a write lock of 1444021689204

In terms of time, 10000ms is also 10s, and the code is consistent, proving that reading and writing are mutually exclusive. Note that "Read and write mutexes" and "Write and read mutexes" are two different scenarios, but the proofs and conclusions are consistent, so it is not proven.

Comparison of synchronized and Reentrantlock

By now, there are 2 ways of locking in multiple threads: synchronized and Reentrantlock. Two kinds of locking methods have advantages and disadvantages, the following simple comparison:

1, synchronized is the key word, and if...else ... , it is a syntax-level implementation, so synchronized acquisition and release locks are all Java virtual machines help the user to complete, Reentrantlock is a class-level implementation, so lock acquisition and the release of locks require the user to operate on their own. Special remind again, Reentrantlock in Lock () is finished, must be manual unlock ()

2, synchronized simple, simple means not flexible, and the Reentrantlock lock mechanism for users to provide a great deal of flexibility. This is vividly reflected in Hashtable and Concurrenthashmap. Synchronized locks the entire hash table, while the Concurrenthashmap uses Reentrantlock to realize the lock separation, the knowledge of the lock segment instead of the entire hash table

3, synchronized is not fair lock, and Reentrantlock can specify whether the lock is fair or not fair

4, synchronized implementation of the waiting/notification mechanism notification thread is random, reentrantlock implementation wait/notification mechanism can selectively notify

5, compared with synchronized, Reentrantlock provides users with a variety of methods for lock information acquisition, such as can know if lock is acquired by the current thread, lock is called by the same thread several times, lock is taken by any thread and so on

To sum up, I think if you only need to lock simple methods, simple code blocks, then consider using synchronized, complex multithreaded processing scenarios can consider using Reentrantlock. Of course, this is only a suggestion, or to specific scenarios specific analysis.

Finally, see a lot of information, JDK1.5 version only because of synchronized did a lot of optimization, efficiency synchronized and reentrantlock should be similar.

Java Multi-Threading 13: Read and write Locks vs. two synchronization modes

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.