如果接觸過多線程編程或者大規模並發應用的開發的人都應該知道Readers-writer lock的設計模式,從英文字面上看就是對於資源允許多個Reader(復數)並發讀,單個Writer寫的鎖機制,而Reader和Writer互斥。
現在的JDK裡有一個ReadWriteLock的接口和一個ReentrantReadWriteLock的實現類,而其作者是赫赫有名的Doug Lea大牛(他有本 Concurrent Programming in Java Design Principles and Pattern ,推薦一下) 。早在JDK 1.4的時代,他就發表了自己的cocurrent包實現,其中就有多個ReadWriteLock的實現。下面會先聊一下早期Doug Lea在EDU.oswego.cs.dl.util.concurrent版本中對ReadWriteLock的實現,最後再說JDK版本的。
1.EDU.oswego.cs.dl.util.concurrent的實現
Doug Lea的這個版本:EDU.oswego.cs.dl.util.concurrent包中ReadWriteLock所包含的內容比JDK要豐富不少,除了ReentrantReadWriteLock還有若干個其他實現。先看一下ReadWriteLock在其中的類繼承關系。源代碼下載
這其中包含了4個ReadWriteLock,包括先進先出的FIFOReadWriteLock ,Writer優先的WriterPreferenceReadWriteLock ,Reader優先的ReaderPreferenceReadWriteLock ,可重入ReentrantWriterPreferenceReadWriteLock 。
1.1 EDU.oswego.cs.dl.util.concurrent.ReadWriteLock接口
Java代碼
- public interface ReadWriteLock {
- /** get the readLock **/
- Sync readLock();
- /** get the writeLock **/
- Sync writeLock();
- }
ReadWriteLock的接口定義和後來JDK的實現基本一致。readLock和writeLock都實現Sync接口,這個接口兩個主要的方法是acquire和realse,在以後的JDK中,變成了Lock的lock方法和unlock方法。
1.2 WriterPreferenceReadWriteLock類
這個類包含了WriterLock類型的writerLock_和ReaderLock類型的readerLock_兩個成員,而這兩個類型又分別為WriterPreferenceReadWriteLock的內部類,這樣做的一個考慮可能是為了能夠讓這兩個類能夠訪問WriterPreferenceReadWriteLock的成員以及互相訪問。
先看看WriterPreferenceReadWriteLock中ReaderLock的實現
該類的幾個成員以及解釋如下
Java代碼
- /*用來給Writer判斷是否可以拿到write控制權*/
- protected long activeReaders_ = 0;
- /*當前writer線程*/
- protected Thread activeWriter_ = null;
- /*可以用來作為策略調整,此版本中沒有太多作用*/
- protected long waitingReaders_ = 0;
- /*等待中的寫,用來給Reader判斷是否還有Writer在等待,以便實現Writer優先*/
- protected long waitingWriters_ = 0;
- /*實際的ReaderLock*/
- protected final ReaderLock readerLock_ = new ReaderLock();
- /*實際的WriterLock*/
- protected final WriterLock writerLock_ = new WriterLock();
先來看看 ReaderLock,它的兩個主要方法acquire和release
其中acquire的代碼如下
Java代碼
- public void acquire() throws InterruptedException {
- if (Thread.interrupted())
- throw new InterruptedException();
- InterruptedException IE = null;
- synchronized (this) {
- /**
- * 判斷是否能夠獲得讀權
- */
- if (!startReadFromNewReader()) {
- for (;;) {
- try {
- /**
- * 等待notify
- */
- ReaderLock.this.wait();
- /**
- * 再次判斷能否獲得讀權
- * 因為此處是Writer優先,當一個writer釋放時,
- * reader還必須等待其他wait的writer獲得控制權並釋放後才能獲得控制權
- */
- if (startReadFromWaitingReader())
- return;
- } catch (InterruptedException ex) {
- cancelledWaitingReader();
- IE = ex;
- break;
- }
- }
- }
- }
- if (IE != null) {
- // fall through outside synch on interrupt.
- // This notification is not really needed here,
- // but may be in plausible subclasses
- writerLock_.signalWaiters();
- throw IE;
- }
- }
acquire調用startReadFromNewReader,startReadFromWaitingReader,以及allowReader方法,這三個方法都屬於WriterPreferenceReadWriteLock類
Java代碼
- protected synchronized boolean startReadFromNewReader() {
- boolean pass = startRead();
- if (!pass)
- ++waitingReaders_;
- return pass;
- }
- protected synchronized boolean startReadFromWaitingReader() {
- boolean pass = startRead();
- if (pass)
- --waitingReaders_;
- return pass;
- }
- protected boolean allowReader() {
- //通過是否有正有控制權的activeWriter_和等待中的waitingWriters_來判斷是Reader是否能獲得控制權
- return activeWriter_ == null && waitingWriters_ == 0;
- }
- protected synchronized boolean startRead() {
- boolean allowRead = allowReader();
- if (allowRead)
- ++activeReaders_;
- return allowRead;
- }
另外release的代碼如下
Java代碼
- public void release() {
- Signaller s = endRead();
- if (s != null)
- s.signalWaiters();
- }
- protected synchronized Signaller endRead() {
- //只有當沒有Reader在控制以及有等待的Writer的時候才返回
- //因為Reader之間沒有互斥,所以返回writerLock
- if (--activeReaders_ == 0 && waitingWriters_ > 0)
- return writerLock_;
- else
- return null;
- }
這裡要注意的是endRead返回的是writerLock,這樣他就可以完成notify和它互斥的writer
下面看一下WriterLock的實現,同樣也是acquire和release方法
先看acquire
Java代碼
- public void acquire() throws InterruptedException {
- if (Thread.interrupted())
- throw new InterruptedException();
- InterruptedException IE = null;
- synchronized (this) {
- //試圖獲得writer權
- if (!startWriteFromNewWriter()) {
- for (;;) {
- try {
- WriterLock.this.wait();
- /**
- * 重新判斷是否能獲得控制權
- * 這時如果是writerLock的notify的話,理論上只有一個reader或者writer能夠結束等待
- * 如果是readerLock的notify的話,因為調用的是notifyAll,所以就必須重新競爭控制權
- */
- if (startWriteFromWaitingWriter())
- return;
- } catch (InterruptedException ex) {
- cancelledWaitingWriter();
- WriterLock.this.notify();
- IE = ex;
- break;
- }
- }
- }
- }
- if (IE != null) {
- // Fall through outside synch on interrupt.
- // On exception, we may need to signal readers.
- // It is not worth checking here whether it is strictly
- // necessary.
- readerLock_.signalWaiters();
- throw IE;
- }
- }
再看acquire調用的startWriteFromNewWriter,startWriteFromWaitingWriter和startWrite
Java代碼
- protected synchronized boolean startWriteFromNewWriter() {
- boolean pass = startWrite();
- //如果不能獲得控制權,則等待數+1
- if (!pass)
- ++waitingWriters_;
- return pass;
- }
- protected synchronized boolean startWrite() {
- // The allowWrite expression cannot be modifIEd without
- // also changing startWrite, so is hard-wired
- //是否能獲得寫控制取決與是否已經有人有控制權(包括讀和寫)
- boolean allowWrite = (activeWriter_ == null && activeReaders_ == 0);
- if (allowWrite)
- activeWriter_ = Thread.currentThread();
- return allowWrite;
- }
- protected synchronized boolean startWriteFromWaitingWriter() {
- boolean pass = startWrite();
- //如果能獲得控制權,則等待數-1
- if (pass)
- --waitingWriters_;
- return pass;
- }
再來看看WriterLock的release實現
Java代碼
- public void release() {
- Signaller s = endWrite();
- if (s != null)
- //如果沒有write的waiter,返回的的是readerLock_,則通知所有waiting的reader結束等待
- //如果有write的waiter,返回的的是writeLock,則通知一個正在等待的writer獲得控制權
- s.signalWaiters();
- }
- protected synchronized Signaller endWrite() {
- activeWriter_ = null;
- //如果沒有writer,則通知所有的等待的reader
- if (waitingReaders_ > 0 && allowReader())
- return readerLock_;
- //優先通知一個等待的writer
- else if (waitingWriters_ > 0)
- return writerLock_;
- else
- return null;
- }
最後看看WriterLock和ReaderLock如何實現Writer優先
* 首先在競爭控制權時,Reader在競爭控制權必須確認既沒有占用控制權的Writer也沒有等待控制權的writer
這裡是調用的是allowRead方法
activeWriter_ == null && waitingWriters_ == 0;
* 其次在WriterLock的release方法裡,調用endWrite,然後也會調用allowReader,確認沒有等待的Writer才會返回readerLock_,並在signalWaiters裡調用notifyAll通知所有的等待reader結束等待。而一旦有writer等待,則調用writerLock_,只通知等待的writer競爭控制權。具體代碼見上文。
* 同時在ReaderLock的release方法裡,調用endRead,返回writerLock_,通知等待的writer競爭控制權。具體代碼見上文。
到此為止WriterPreferenceReadWriteLock的實現基本說完,這個版本的實現下載見http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.Html