Home > Java > javaTutorial > body text

What is the concept of java read-write lock

WBOY
Release: 2023-05-13 23:01:04
forward
808 people have browsed it

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

2. Because of read-write locks, read and write operations between multiple threads will not conflict.

3. ReadWriteLock is a read-write lock. It is an interface. RentrantReadWriteLock implements this interface.

Example

public class CacheDemo {
    private Map<String, Object> cache = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 
    public static void main(String[] args) {
 
 
    }
 
    public Object getData(String key) {
 
        Object value = null;
        //首先开启读锁,从缓存中去取
        readWriteLock.readLock().lock();
        try {
            value = cache.get(key);
            //如果缓存中没有释放读锁,上写锁
            if (value == null) {
                //对应queryDB()
                readWriteLock.readLock().unlock();
                //读锁必须unlock之后才能获取写锁
                readWriteLock.writeLock().lock();
                try {
                    //对应queryDB()
                    value = queryDB();
                } finally {
                    //释放写锁
                    readWriteLock.writeLock().unlock();
                }
                //然后再上读锁
                readWriteLock.readLock().lock();
            }
        } finally {
            //最后释放读锁
            readWriteLock.readLock().unlock();
        }
        return value;
 
    }
 
    public Object queryDB() {
        return "aaaa";
    }
}
Copy after login

The above is the detailed content of What is the concept of java read-write lock. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!