Home  >  Article  >  Java  >  What is the concept of java read-write lock

What is the concept of java read-write lock

WBOY
WBOYforward
2023-05-13 23:01:04811browse

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";
    }
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete