Get the App
SLTechnology News&Howtos  ›  Development  › 

What is a java read-write lock

Shulou Source: shulou.com Published: 2022-06-03 03:15:24 09月29日 Update

This article mainly explains "what is a java read-write lock". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is a java read-write lock".

1. Read-write locks divide the access to a resource (such as a file) into two locks, one read-write lock.

2. Because of the read-write lock, read-write operations between multiple threads will not conflict.

3. ReadWriteLock is a read-write lock, which is an interface that RentrantReadWriteLock implements.

Example

Public class CacheDemo {private Map cache = new HashMap (); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock (); public static void main (String [] args) {} public Object getData (String key) {Object value = null; / / first open the read lock and fetch readWriteLock.readLock () .lock (); try {value = cache.get (key) / / if the read lock is not released in the cache, the write lock if (value = = null) {/ / corresponds to queryDB () readWriteLock.readLock () .unlock (); / / the read lock must be unlock before the write lock readWriteLock.writeLock () .lock () Try {/ / corresponds to queryDB () value = queryDB ();} finally {/ / release write lock readWriteLock.writeLock () .unlock () } / / then readWriteLock.readLock (). Lock ();}} finally {/ / finally release the read lock readWriteLock.readLock (). Unlock ();} return value;} public Object queryDB () {return "aaaa" }} Thank you for your reading. the above is the content of "what is java read-write lock". After the study of this article, I believe you have a deeper understanding of what java read-write lock is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Learning content interface cache between multiple examples that is ideas situations files articles more knowledge knowledge points articles threads resources follow Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi macOS OPPO Reno Linux MariaDB