Lock application-read/write Lock

Source: Internet
Author: User

Both internal locks and locks are exclusive locks or exclusive locks, that is, read/write mutex, read mutex; another Lock opposite to exclusive locks is a shared Lock, java ReadWriteLock is a shared lock that provides read and write sharing, but read and write are still mutually exclusive.


The biggest feature of ReadWriteLock is reading and sharing. For example, if the read lock of thread A is being read, if thread B requests the read lock, thread B can immediately obtain the read lock without waiting, however, if the C thread requests a write lock, the C thread needs to wait for the lock to be available. ReadWriteLock increases the complexity of reading and sharing, so the scenarios with frequent reading and writing cannot reflect the performance advantages, only when there are a lot of reading operations and few write operations can the performance advantages be reflected. For example, after an application system is installed, a batch of maintenance initialization data needs to be imported. The data can be modified through the interface, but few changes are required, when the system starts, it will automatically load the initialization data to the specified data structure, such as HashMap) for reading and using by each module, so you can add ReadWriteLock to read and write the data, to improve reading performance and maintain data consistency.


The ReentrantReadWriteLock class is an implementation of the ReadWriteLock interface. Like the ReentrantLock class, it provides two mechanisms: fair competition and unfair competition. By default, it also uses unfair competition. ReentrantLock is an exclusive lock. When an unfair competition mechanism is used, there are relatively few opportunities to seize the lock. Only when new requests coincide with the lock release will they have the opportunity to seize the lock, as a result, thread hunger rarely occurs. However, ReentrantReadWriteLock is a shared lock, or a read-and-share function, which is often used in scenarios with more reads and less writes. That is, the threads that request read operations are large and frequent, while the threads that request write operations are few and have a long interval, in this scenario, the use of unfair competition mechanism is very likely to cause writing thread hunger. For example, when the R1 thread holds the read lock and performs the read operation, the W1 thread requests the write lock so it needs to wait in queue. Before R1 releases the lock, if R2, R3 ,..., rn keeps coming to request read locks. Because of read sharing, they don't have to wait for the lock to be obtained immediately. In this way, W1 will never be able to get the write lock and will remain hungry. Therefore, when using the ReentrantReadWriteLock class, be careful to choose a fair mechanism to avoid unexpected results.


Finally, the implementation of the read/write lock of Java 5 is flawed and may cause a deadlock. It has been fixed in Java 6, so avoid using the read/write lock of Java 5.


Sample Code:

Import java. util. hashMap; import java. util. concurrent. timeUnit; import java. util. concurrent. locks. readWriteLock; import java. util. concurrent. locks. reentrantReadWriteLock; public class TestReadWriteLock {private static final int MAX_INDEX = 100; private HashMap <Integer, Integer> mInitDataMap; private ReadWriteLock mRWlock; private volatile boolean isNonStop; public void start. isNonStop = true;} public void stop () {this. isNonStop = false;} public TestReadWriteLock () {init ();} private void init () {mInitDataMap = new HashMap <Integer, Integer> (MAX_INDEX ); mRWlock = new ReentrantReadWriteLock (); for (int I = 0; I <MAX_INDEX; I ++) {mInitDataMap. put (I, I) ;}} private class Reader implements Runnable {@ Override public void run () {while (isNonStop) {mRWlock. readLock (). lock (); System. out. println (Thread. currentThread (). getName () + ": get the read lock. "); try {mInitDataMap. get (int) (MAX_INDEX-1) * Math. random (); // read time is added here to make the write thread more vulnerable to hunger/* try {TimeUnit. MILLISECONDS. sleep (long) (1000 * Math. random ();} catch (InterruptedException e) {e. printStackTrace ();} */} finally {mRWlock. readLock (). unlock () ;}}} private class Writer implements Runnable {@ Override public void run () {while (isNonStop) {mRWlock. writeLock (). lock (); System. out. println (Thread. currentThread (). getName () + ": get the write lock. "); try {mInitDataMap. put (int) (MAX_INDEX-1) * Math. random (), (int) (MAX_INDEX-1) * Math. random (); // read time is added here to make the write thread more vulnerable to hunger/* try {TimeUnit. MILLISECONDS. sleep (long) (1000);} catch (InterruptedException e) {e. printStackTrace ();} */} finally {mRWlock. writeLock (). unlock () ;}}} public static void main (String [] args) throws InterruptedException {TestReadWriteLock testReadWriteLock = new TestReadWriteLock (); testReadWriteLock. start (); for (int I = 0; I <5 * MAX_INDEX; I ++) {new Thread (testReadWriteLock. new Reader ()). start ();} new Thread (testReadWriteLock. new Writer ()). start (); TimeUnit. SECONDS. sleep (5); testReadWriteLock. stop ();}}


This article is from "the power comes from the sincere love !" Blog, please be sure to keep this source http://stevex.blog.51cto.com/4300375/1301216

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.