Read-write lock
Concurrent reading, exclusive writing, deadlocking of read locks and write locks may occur.
A resource can be accessed by multiple read threads, or by one writer thread, but cannot exist at the same time. Read-write mutual exclusion, write-write mutual exclusion Exclusion, read and read sharing.
shortcoming:
- Cause lock starvation, keep reading, unable to write operations, such as taking the subway, 100 people get on the bus and 1 person gets off, and it is blocked all the time.
- When reading, no thread can write. When writing, its own thread can read, and other threads cannot read
ps: a read-write lock is essentially a spin lock
Code Example: Cache Read and Write
//资源类
class MyCache{
private volatile Map<String, Object> map = new HashMap<>();
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
//放数据
public void put(String key, Object value) {
//添加写锁
try {
rwLock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + "+++正在写操作");
//模拟写的很慢
TimeUnit.MICROSECONDS.sleep(300);
//放数据
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "+++写操作完成√√√√");
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
//释放写锁
rwLock.writeLock().unlock();
}
}
//取数据
public Object get(String key) {
Object result = null;
//模拟取的很慢
try {
rwLock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "---读取操作");
TimeUnit.MICROSECONDS.sleep(300);
result = map.get(key);
System.out.println(Thread.currentThread().getName() + "---取完了" + key + "::" + result);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
rwLock.readLock().unlock();
}
return result;
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCache = new MyCache();
//放数据线程
for (int i = 1; i <= 5; i++) {
final int num = i;
new Thread(()->{
myCache.put(String.valueOf(num), String.valueOf(num));
},String.valueOf(i)).start();
}
//取数据线程
for (int i = 1; i <= 5; i++) {
final int num = i;
new Thread(()->{
myCache.get(String.valueOf(num));
},String.valueOf(i)).start();
}
}
}
Lock downgrade: downgrade a write lock to a read lock
Code example lock downgrade
Write lock downgraded to read lock
public class 锁降级Demo {
public static void main(String[] args) {
//可重入读写锁对象
ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
//锁降级 , 写的时候在此线程还能获取到读锁,而读的时候不能获取到写锁
//1.获取写锁
writeLock.lock();
System.out.println("哈哈哈");
//2.获取写锁
readLock.lock();
System.out.println("read");
//3.释放写锁
writeLock.unlock();
//4.释放读锁
readLock.unlock();
}
}