欢迎访问昆山宝鼎软件有限公司网站! 设为首页 | 网站地图 | XML | RSS订阅 | 宝鼎邮箱 | 后台管理


新闻资讯

MENU

软件开发知识

再谈 AbstractQueuedSynchron 昆山软件定制开发 izer 3 :基于 AbstractQueued

点击: 次  来源:宝鼎软件 时间:2017-08-17

原文出处: 五月的仓颉

公正模式ReentrantLock实现道理

前面的文章研究了AbstractQueuedSynchronizer的独有锁和共享锁,有了前两篇文章的基本,就可以乘胜追击,看一下基于AbstractQueuedSynchronizer的并发类是如何实现的。

ReentrantLock显然是一种独有锁,首先是公正模式的ReentrantLock,Sync是ReentractLock中的基本类,担任自AbstractQueuedSynchronizer,看一下代码实现:

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

    protected final boolean isHeldExclusively() {
        // While we must in general read state before owner,
        // we don't need to do so to check if current thread is owner
        return getExclusiveOwnerThread() == Thread.currentThread();
    }

    final ConditionObject newCondition() {
        return new ConditionObject();
    }

    // Methods relayed from outer class

    final Thread getOwner() {
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }

    final int getHoldCount() {
        return isHeldExclusively() ? getState() : 0;
    }

    final boolean isLocked() {
        return getState() != 0;
    }

    /**
     * Reconstitutes this lock instance from a stream.
     * @param s the stream
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

Sync属于一个民众类,它是抽象的说明Sync会被担任,简朴整理一下Sync主要做了哪些事(因为Sync不是ReentrantLock公正锁的要害):

  1. 界说了一个lock要领让子类去实现,我们平时之所以能挪用ReentrantLock的lock()要领,就是因为Sync界说了它
  2. 实现了非公正锁tryAcquira的要领
  3. 实现了tryRelease要领,较量简朴,状态-1,独有锁的线程置空
  4. 实现了isHeldExclusively要领
  5. 界说了newCondition要领,让开拓者可以操作Condition实现通知/期待

接着,看一下公正锁的实现,FairSync类,它担任自Sync:

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

整理一下要点:

1. 每次acquire的时候,state+1,假如当前线程lock()之后又lock()了,state不绝+1,相应的unlock()的时候state-1,直到将state减到0为之,说明当前线程释放完所有的状态,其它线程可以竞争

2. state=0的时候,通过hasQueuedPredecessors要领做一次判定,hasQueuedPredecessors的实现为”h != t && ((s = h.next) == null || s.thread != Thread.currentThread());”,个中h是head、t是tail,由于代码中对功效取反,因此取反之后的判定为”h == t || ((s = h.next) != null && s.thread == Thread.currentThread());”,总结起来有两种环境可以通过!hasQueuedPredecessors()这个判定:

  • h==t,h==t的环境为要么当前FIFO行列中没有任何数据,要么只构建出了一个head还没往后头连过任何一个Node,因此head就是tail
  • (s = h.next) != null && s.thread == Thread.currentThread(),当前线程为正在期待的第一个Node中的线程
  • 3. 假如没有线程比当前线程期待更久去执行acquire操纵,那么通过CAS操纵将state从0变为1的线程tryAcquire乐成