Java read/write lock (reentrantreadwritelock) Learning

Source: Internet
Author: User

What is a read-write lock

In peacetime, our common synchronized and reentrantlock are basically exclusive locks, which allow only one thread to access it at the same time, even if it is a read operation. The read-write lock maintains a pair of locks (a read lock and a write lock), allowing multiple read threads to be accessed at the same time by separating the read and write locks, but all read and other write threads are blocked when the write thread accesses.

Advantages of Read and write locks

1. Simplifies the complexity of programming for read-write interaction scenarios:

In common development, we often define a shared data structure used as a cache, such as a large map that caches all city IDs and city name correspondence. Most of the time the big map provides read service (query city names based on city ID, etc.), while write operations take up very little time, typically initialized at service startup, and then refresh the cached data at regular intervals. However, the start of the write operation between the end, there can be no additional read operation, and the completion of the write operation after the update data needs to be visible to subsequent read services.

In the absence of read-write lock support, if the need to complete the above work will use the Java waiting notification mechanism, that is, when the write operation begins, all the read operation later than the write operation will go to the waiting state, only after the write operation is completed and notified, all the waiting read operations can continue to execute ( Multiple writes depend on the Synchronized keyword for synchronization, which is done to enable the read operation to read the correct data without any dirty reads. The use of read-write locks to achieve the above functions, which only need to read the operation to obtain a read lock, write operations to obtain a write lock. When a write lock is acquired, the read and write locks of subsequent (non-current) threads are blocked, and after the write lock is released, all operations continue, programmatically relative to the implementation using the wait-for-notification mechanism. Become simple and clear.

2. Increased throughput of the program:

Read and write locks use different locks through read and write, and reading operations use shared locks, and write operations use exclusive locks, allowing programs to provide better concurrency and throughput. Read-write locks provide better performance than lock locks in cases where reading is more than writing.

Characteristics of Reentrantreadwritelock
features Description
Fairness Options Support for unfair (default) and fair lock acquisition, throughput or unfair better than fairness
Re-entry The lock supports re-entry, taking a read-write thread as an example: the read thread can acquire a read lock again after it acquires a read lock. The write thread acquires a write lock and can acquire a read lock once it acquires a write lock.
Lock downgrade Allow to downgrade from write lock to read lock, when implemented: first obtain a write lock, then obtain a read lock, finally release the write lock, this will be a write lock. However, it is not possible to upgrade from a read lock to a write lock
Condition support A write lock provides a condition implementation that behaves the same as the condition implementation provided by Reentrantlock.newcondition () for a write lock. Of course, this condition can only be used for write locks. Read locks do not support Condition,readlok (). Newcondition () will throw unsupportedoperationexception.
Monitoring These methods are mainly used to monitor the state of the system, rather than synchronous control
Use case
 Public classreentrantreadwritelocktest {Private Staticmap<string, object> map =NewHashmap<> ();Private StaticReentrantreadwritelock RWL =NewReentrantreadwritelock ();Private StaticLock Readlock = rwl.Readlock();Private StaticLock Writelock = rwl.Writelock(); Public Static void Main(string[] args) {Reentrantreadwritelocktest Reentrantreadwritelocktest =New reentrantreadwritelocktest() ; Executor Executor = executors.Newfixedthreadpool(4) ; Executor.Execute(() {System. out.println("Write lock Start"); Reentrantreadwritelocktest.put("1","1") ; System. out.println("Write lock End");        }); Executor.Execute(() {System. out.println("read lock start"); System. out.println(Reentrantreadwritelocktest.Get("4")); System. out.println("read lock End");        }); Executor.Execute(() {System. out.println("Write lock Start"); Reentrantreadwritelocktest.put("3","3") ; System. out.println("Write lock Start");        }); Executor.Execute(() {System. out.println(Reentrantreadwritelocktest.Get("1"));    }); } Public void put(string key, String value) {Try{Writelock.Lock(); Map.put(key, value); }finally{Writelock.Unlock(); }    } PublicObjectGet(String key) {Try{Readlock.Lock();returnMap.Get(key); }finally{Readlock.Unlock(); }    }}

Java read/write lock (reentrantreadwritelock) Learning

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.