您的位置:首页 > 编程语言 > Java开发

java.util.concurrent.locks.ReentrantLock 源码剖析

2017-02-28 22:32 661 查看
ReentrantLock从jdk1.5开始引入,相对于synchronized关键字有较好的效率。方法摘要如下:
方法摘要
 int
getHoldCount()
          查询当前线程保持此锁的次数。
protected  Thread
getOwner()
          返回目前拥有此锁的线程,如果此锁不被任何线程拥有,则返回
null
protected  Collection<Thread>
getQueuedThreads()
          返回一个 collection,它包含可能正等待获取此锁的线程。
 int
getQueueLength()
          返回正等待获取此锁的线程估计数。
protected  Collection<Thread>
getWaitingThreads(Condition condition)
          返回一个 collection,它包含可能正在等待与此锁相关给定条件的那些线程。
 int
getWaitQueueLength(Condition condition)
          返回等待与此锁相关的给定条件的线程估计数。
 boolean
hasQueuedThread(Thread thread)
          查询给定线程是否正在等待获取此锁。
 boolean
hasQueuedThreads()
          查询是否有些线程正在等待获取此锁。
 boolean
hasWaiters(Condition condition)
          查询是否有些线程正在等待与此锁有关的给定条件。
 boolean
isFair()
          如果此锁的公平设置为 true,则返回
true
 boolean
isHeldByCurrentThread()
          查询当前线程是否保持此锁。
 boolean
isLocked()
          查询此锁是否由任意线程保持。
 void
lock()
          获取锁。
 void
lockInterruptibly()
          如果当前线程未被中断,则获取锁。
 Condition
newCondition()
          返回用来与此
Lock
实例一起使用的
Condition
实例。
 String
toString()
          返回标识此锁及其锁定状态的字符串。
 boolean
tryLock()
          仅在调用时锁未被另一个线程保持的情况下,才获取该锁。
 boolean
tryLock(long timeout,
TimeUnit unit)
          如果锁在给定等待时间内没有被另一个线程保持,且当前线程未被中断,则获取该锁。
 void
unlock()
          试图释放此锁。
ReentrantLock锁机制通过其内部的Synchronizer实现。Sync继承了AbstractQueueSynchronizer类实现线程同步。ReentrantLock的两个重要方法lock() 和unlock()的实现如下:public void lock() {sync.lock();//调用sync的lock()方法}sync的lock方法在公平的reentrantLock与非公平的reentrantLock中有不同的实现1 lock()(1) no-fair-syncfinal void lock() {if (compareAndSetState(0, 1))//判断是否有线程占用锁,如果没有则将锁状态设置为“被占用”状态
//设置当前线程为拥有锁的线程
setExclusiveOwnerThread(Thread.currentThread());
else//锁被占用
acquire(1);//调用AbstractQueueSynchronizer的acquire(int arg)方法进行进一步判断
}
AbstractQueueSynchronizer的acquire(int arg)方法如下:public final void acquire(int arg) {
//首先调用NonfairSync(或者FairSync)的tryAcquire()方法(在不同的类中有不同的实现),
//如果没有获得锁则调用acquireQueue方法将该线程放入等待列表
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
//no-fair-Sync
 protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);//调用AbstractQueueSynchronizer的nonfairTryAcquire(int acquires) 方法

        }
 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;
        }
(2) fair-Syncfinal void lock() {acquire(1);}
 public final void acquire(int arg) {        if (!tryAcquire(arg) &&            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))            selfInterrupt();    }
 	 /**         * 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;        }    }
2 unlock() 公平锁与非公平锁实现一致public void unlock() {sync.release(1);//调用AbstractQueueSynchronizer的relase方法}
 public final boolean release(int arg) {if (tryRelease(arg)) {//调用Sync的tryReleaseNode h = head;if (h != null && h.waitStatus != 0)unparkSuccessor(h);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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: