ReadWriteLock也是一个接口,提供了readLock和writeLock两种锁的操作机制,一个资源可以被多个线程同时读,或者被一个线程写,但是不能同时存在读和写线程。
基本规则: 读读不互斥 读写互斥 写写互斥
问题: 既然读读不互斥,为何还要加读锁
答: 如果只是读,是不需要加锁的,加锁本身就有性能上的损耗
如果读可以不是最新数据,也不需要加锁
如果读必须是最新数据,必须加读写锁
读写锁相较于互斥锁的优点仅仅是允许读读的并发,除此之外并无其他。
结论: 读写锁能够保证读取数据的 严格实时性,如果不需要这种 严格实时性,那么不需要加读写锁。
简单实现:
package readandwrite; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantReadWriteLock; public class MyTest { private static ReentrantReadWriteLock rwl=new ReentrantReadWriteLock(); private static double data=0; static class readClass implements Runnable{ @Override public void run() { rwl.readLock().lock(); System.out.println("读数据:"+data); rwl.readLock().unlock(); } } static class writeClass implements Runnable{ private double i; public writeClass(double i) { this.i = i; } @Override public void run() { rwl.writeLock().lock(); data=i; System.out.println("写数据: "+data); rwl.writeLock().unlock(); } } public static void main(String[] args) throws InterruptedException { ExecutorService pool=Executors.newCachedThreadPool(); for(int i=0;i<10;i++){ pool.submit(new readClass()); pool.submit(new writeClass((double)new Random().nextDouble())); pool.submit(new writeClass((double)new Random().nextDouble())); Thread.sleep(1000); } pool.shutdown(); } }
之前我们提到的锁都是排它锁(同一时刻只允许一个线程进行访问),而读写锁维护了一对锁,一个读锁,一个写锁。读写锁在同一时刻允许多个线程进行读操作,但是写线程访问过程中,所有的读线程和其他写线程均被阻塞。如此,并发性有了很大的提升。这样,在某些读远远大于写的场景中,读写锁能够提供比排它锁更好的并发量和吞吐量。
一个关于读写锁的Demo:
分析:设计一个模拟队列,拥有一个data成员变量用于存储数据和存取两种操作。
import java.util.Random; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockDemo { public static void main(String[] args) { DefQueue queue = new DefQueue(); for (int i = 1; i < 10; i++) { //启动线程进行读操作 new Thread(new Runnable() { @Override public void run() { while (true) { queue.get(); } } }).start(); //启动线程进行写操作 new Thread(new Runnable() { @Override public void run() { while(true) { queue.put(new Random().nextInt(10000)); } } }).start(); } } } class DefQueue { private int data; ReadWriteLock rwLock = new ReentrantReadWriteLock(); public void get() { rwLock.readLock().lock();//加读锁 try { System.out.println(Thread.currentThread().getName() + "be ready to get data"); Thread.sleep((long) (Math.random() * 1000)); System.out.println(Thread.currentThread().getName() + "get the data: " + data); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwLock.readLock().unlock();//释放读锁 } } public void put(int data) { rwLock.writeLock().lock();//加写锁 try { System.out.println(Thread.currentThread().getName() + " be ready to write data"); Thread.sleep((long) (Math.random() * 1000)); this.data = data; System.out.println(Thread.currentThread().getName() + " has wrote the data: "+data); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwLock.writeLock().unlock();//释放写锁 } } }
程序部分运行结果:
Thread-0be ready to get data Thread-0get the data: 0 Thread-1 be ready to write data Thread-1 has wrote the data: 1156 Thread-2be ready to get data Thread-2get the data: 1156 Thread-3 be ready to write data Thread-3 has wrote the data: 9784 Thread-3 be ready to write data Thread-3 has wrote the data: 4370 Thread-3 be ready to write data Thread-3 has wrote the data: 1533 Thread-4be ready to get data Thread-4get the data: 1533 Thread-5 be ready to write data Thread-5 has wrote the data: 2345 Thread-6be ready to get data Thread-6get the data: 2345 Thread-9 be ready to write data Thread-9 has wrote the data: 9463 Thread-9 be ready to write data Thread-9 has wrote the data: 9301 Thread-9 be ready to write data Thread-9 has wrote the data: 549 Thread-9 be ready to write data Thread-9 has wrote the data: 4673 Thread-9 be ready to write data
我们可以看到打印语句结果很正常。
下面我们再来实现一个模拟缓冲区的小Demo:
import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /* * @author vayne * * 多线程实现缓存的小demo */ class Cachend { volatile Map<String, String> cachmap = new HashMap<String, String>();//加volatile关键字保证可见性。 ReadWriteLock rwLock = new ReentrantReadWriteLock();//这个读写锁要定义在方法外面,使得每一个线程用的是同一个读写锁。 public String getS(String key) //如果定义在方法内部,就是跟方法栈有关的读写锁。这样可能不是同一个锁。 { rwLock.readLock().lock(); String value = null; try { value = cachmap.get(key); if (cachmap.get(key) == null)//这里要重新获得key对应的value值 { rwLock.readLock().unlock(); rwLock.writeLock().lock(); try { if (cachmap.get(key) == null)//这里也是 { value = "" + Thread.currentThread().getName(); cachmap.put(key, value); System.out.println(Thread.currentThread().getName() + " put the value ::::" + value); } } finally { rwLock.readLock().lock(); //将锁降级,这里跟下一句的顺序不能反。 rwLock.writeLock().unlock();//关于这里的顺序问题,下面我会提到。 } } } finally { rwLock.readLock().unlock(); } return cachmap.get(key); } } public class CachendDemo { public static void main(String[] args) { Cachend ca = new Cachend(); for (int i = 0; i < 4; i++) { new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" "+ca.getS("demo1")); System.out.println(Thread.currentThread().getName()+" "+ca.cachmap.entrySet()); } }).start(); } } }
运行结果:
Thread-0 put the value ::::Thread-0 Thread-0 Thread-0 Thread-0 [demo1=Thread-0] Thread-2 Thread-0 Thread-2 [demo1=Thread-0] Thread-3 Thread-0 Thread-3 [demo1=Thread-0] Thread-1 Thread-0 Thread-1 [demo1=Thread-0]
上面我给出了一些注释,其实这个代码是很不好写的,考虑的东西很多。下面我来讲一下上面的代码中提到的顺序问题。
对于读写锁我们应该了解下面的一些性质(这些性质是由源代码得出来的,因为源代码的设计,所以才有下列性质):
第二条对应我们上面的程序就是,如果我们添加了“demo1”对应的value值,然后释放了写锁,此时在当前线程S还未获得读锁时,另一个线程T又获得了写锁,那么就会将S的操作给覆盖(如果取到的值已经缓存在S中,那么T的操作就无法被S感知了,到最后依然会返回S操作的值)。
再来看一个DEMO:
读写锁,分为读锁和写锁,多个读锁不互斥,读锁和写锁互斥,写锁与写锁互斥,这是JVM自己控制的,你只要上好相应的锁即可,如果你的代码只读数据,可以很多人同时读,但不能同时写,那就上读锁;如果你的代码修改数据,只能有一个人在写,且不能同时读取,那就上写锁.总之,读的时候上读锁,写的时候上写锁!
看如下程序: 新建6个线程,3个线程用来读,3个线程用来写,
package javaplay.thread.test; import java.util.Random; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockTest { public static void main(String[] args) { final Queue3 q3 = new Queue3(); for (int i = 0; i < 3; i++) { new Thread() { public void run() { while (true) { q3.get(); } } }.start(); new Thread() { public void run() { while (true) { q3.put(new Random().nextInt(10000)); } } }.start(); } } } class Queue3 { private Object data = null;// 共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。 // 读写锁 ReadWriteLock rwl = new ReentrantReadWriteLock(); // 相当于读操作 public void get() { rwl.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + " be ready to read data!"); Thread.sleep((long) (Math.random() * 1000)); System.out.println(Thread.currentThread().getName() + "have read data :" + data); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwl.readLock().unlock(); } } // 相当于写操作 public void put(Object data) { rwl.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + " be ready to write data!"); Thread.sleep((long) (Math.random() * 1000)); this.data = data; System.out.println(Thread.currentThread().getName() + " have write data: " + data); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwl.writeLock().unlock(); } } }
读写锁功能很强大!这样可以实现正常的逻辑,如果我们把读写锁相关的代码注释,发现程序正准备写的时候,就有线程读了,发现准备读的时候,有线程去写,这样不符合我们的逻辑;通过Java5的新特新可以很轻松的解决这样的问题;
查看Java API ReentrantReadWriteLock 上面有经典(缓存)的用法,下面是doc里面的伪代码,,它演示的是一个实体的缓存,不是缓存系统,相当于缓存代理,注意volatile的运用:
package javaplay.thread.test; import java.util.concurrent.locks.ReentrantReadWriteLock; /* * Sample usages. Here is a code sketch showing how to perform lock downgrading after updating a cache * (exception handling is particularly tricky when handling multiple locks in a non-nested fashion): */ class CachedData { Object data; volatile boolean cacheValid; final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // Must release read lock before acquiring write lock rwl.readLock().unlock(); rwl.writeLock().lock(); try { // Recheck state because another thread might have // acquired write lock and changed state before we did. if (!cacheValid) { data = ... cacheValid = true; } // Downgrade by acquiring read lock before releasing write lock rwl.readLock().lock(); } finally { rwl.writeLock().unlock(); // Unlock write, still hold read } } try { use(data); } finally { rwl.readLock().unlock(); } } }
假设现在多个线程来读了,那第一个线程读到的数据是空的,那它就要写就要填充数据,那么第二个第三个就应该互斥等着,一进来是来读数据的所以上读锁,进来后发现数据是空的,就先把读锁释放再重新获取写锁,就开始写数据,数据写完了,就把写锁释放,把读锁重新挂上,持有读锁时不能同时获取写锁,但拥有写锁时可同时再获取读锁,自己线程挂的写锁可同时挂读锁的,这就是降级,就是除了读锁和写锁外,还有读写锁也叫更新锁,就是自己即可以读又可以写的锁,也就是在自己拥有写锁还没释放写锁时就获取了读锁就降级为读写锁/更新锁,但是不能在持有读锁时再获取写锁;
基于上面的例子,我们可以实现一个缓存系统:
package javaplay.thread.test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class CacheDemo { private Map<String, Object> cache = new HashMap<>(); public static void main(String[] args) { } // 可做到多个线程并必的读 读和写又互斥 系统性能很高 // 这就是读写锁的价值 private ReadWriteLock rwl = new ReentrantReadWriteLock(); public Object getData(String key) { rwl.readLock().lock(); Object value = null; try { value = cache.get(key); if (value == null) {// 避免首次多次查询要加synchronized rwl.readLock().unlock(); rwl.writeLock().lock(); try { if (value == null) // 就算第二个第三个线程进来时也不用再写了 跟伪代码相同原理 value = "aaa";// 实际去query db } finally { rwl.writeLock().unlock(); } rwl.readLock().lock(); } } finally { rwl.readLock().unlock(); } return value; } } 错误之处:没有把不存在的值put;要用get(key)来判空
感谢大家对呐喊教程的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。