java學習之ReentrantLock

來源:互聯網
上載者:User

標籤:tran   dia   存在   flow   less   rac   ==   help   extend   

 本篇博文主要記錄ReentranctLock內部實現原理。

 

ReentrantLock和Synchronized關鍵字相比,使用起來比較靈活。如何使用ReentranctLock就不多講了,這裡主要記錄ReentrantLock的內部實現原理。

首先看下ReentrantLock的類繼承結構, 如:

 

ReentrantLock內部有三個內部類: Sync, FairSync, NonfairSync. 源碼如下:

Sync:

abstract static class Sync extends AbstractQueuedSynchronizer {        private static final long serialVersionUID = -5179523762034025860L;        /**         * Performs {@link Lock#lock}. The main reason for subclassing         * is to allow fast path for nonfair version.         */        abstract void lock();        /**         * Performs non-fair tryLock.  tryAcquire is implemented in         * subclasses, but both need nonfair try for trylock method.         */        final boolean nonfairTryAcquire(int acquires) {            final Thread current = Thread.currentThread();            int c = getState();            if (c == 0) {                if (compareAndSetState(0, acquires)) {                    setExclusiveOwnerThread(current);                    return true;                }            }            else if (current == getExclusiveOwnerThread()) {                int nextc = c + acquires;                if (nextc < 0) // overflow                    throw new Error("Maximum lock count exceeded");                setState(nextc);                return true;            }            return false;        }        protected final boolean tryRelease(int releases) {            int c = getState() - releases;            if (Thread.currentThread() != getExclusiveOwnerThread())                throw new IllegalMonitorStateException();            boolean free = false;            if (c == 0) {                free = true;                setExclusiveOwnerThread(null);            }            setState(c);            return free;        }
...}

  FairSync:

static final class FairSync extends Sync {        private static final long serialVersionUID = -3000897897090466540L;        final void lock() {            acquire(1);        }        /**         * Fair version of tryAcquire.  Don‘t grant access unless         * recursive call or no waiters or is first.         */        protected final boolean tryAcquire(int acquires) {            final Thread current = Thread.currentThread();            int c = getState();            if (c == 0) {                if (!hasQueuedPredecessors() &&                    compareAndSetState(0, acquires)) {                    setExclusiveOwnerThread(current);                    return true;                }            }            else if (current == getExclusiveOwnerThread()) {                int nextc = c + acquires;                if (nextc < 0)                    throw new Error("Maximum lock count exceeded");                setState(nextc);                return true;            }            return false;        }    }

  NonfairSync:

static final class NonfairSync extends Sync {        private static final long serialVersionUID = 7316153563782823691L;        /**         * Performs lock.  Try immediate barge, backing up to normal         * acquire on failure.         */        final void lock() {            if (compareAndSetState(0, 1))                setExclusiveOwnerThread(Thread.currentThread());            else                acquire(1);        }        protected final boolean tryAcquire(int acquires) {            return nonfairTryAcquire(acquires);        }    }

  

FairSync實現了公平鎖邏輯, NonfairSync實現的是非公平鎖的邏輯。 下面看下最常使用的非公平鎖的實現。

NonfairSync.lock()方法,首先基於CAS設定AQS中的state,如果返回true, 說明擷取成功,此時將排他線程設定為當前線程。如果返回false, 說明擷取失敗,調用acquire(1)方法。acquire()方法在AQS中,代碼如下:

    public final void acquire(int arg) {        if (!tryAcquire(arg) &&            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))            selfInterrupt();    }

  在acquire中首先再次擷取鎖, 如果擷取失敗, 則調用addWaiter()方法,將當前線程加入CHL隊列。CHL隊列結構如下:

 

排入佇列後,然後調用方法acquireQueued(), 代碼如下:

final boolean acquireQueued(final Node node, int arg) {        boolean failed = true;        try {            boolean interrupted = false;            for (;;) {                final Node p = node.predecessor();                if (p == head && tryAcquire(arg)) {                    setHead(node);                    p.next = null; // help GC                    failed = false;                    return interrupted;                }                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    interrupted = true;            }        } finally {            if (failed)                cancelAcquire(node);        }    }

在acquireQueued()方法中,首先判斷當前節點的前置節點是不是頭結點,如果是頭結點,則嘗試擷取鎖,擷取成功,則當前節點設定為頭結點。否則判斷是否應該講當前節點對應的線程掛起, 如果前一個前一個節點的status是SIGNAL, 則說明需要將當前節點掛起。調用parkAndCheckInterrupt()方法掛起當前節點的線程。

 

上面是非公平鎖的lock()邏輯,公平鎖和非公平鎖的,區別主要是公平鎖在擷取之前,首先需要判斷是否存在前置節點,如果存在前置節點,則需要等待。我們看到FairSync中的tryAcquire()方法中,首先調用了hasQueuedPredecessors()方法,判斷是否存在前置節點。

 

java學習之ReentrantLock

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.