ReentrantLockd的非公平锁lock方法实现源码解析 博客分类: java多线程 java
程序员文章站
2024-03-20 15:46:58
...
//ReetrantLock源码解析: Lock lock = new ReentrantLock(); try { lock.lock(); ....doSomething } finally { lock.unlock(); } //先从我们最常用的这个lock()方法开始.从非公平模式来看lock的实现, public void lock() { sync.lock(); //委托到sync对象实现. } //sync的实现 abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -5179523762034025860L; //抽象方法主要就是实现它 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: static final class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; //OK 找到实现方法 final void lock() { //利用CAS机制将state值设置为1即如果AbstractQueuedSynchronizer中的state为0,设置为1 if (compareAndSetState(0, 1)) //成功.设置当前的线程为排他线程 setExclusiveOwnerThread(Thread.currentThread()); else //尝试以独占方式获取对象。 acquire(1); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } //调用AbstractQueuedSynchronizer中的acquire方法 public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } //调用tryAcquire protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } //然后就是调用这个方法 final boolean nonfairTryAcquire(int acquires) { //获取当前的线程 final Thread current = Thread.currentThread(); int c = getState(); //获取当前state状态,如果是0则可以获取锁(其他线程已经释放了资源)。 if (c == 0) { if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } //当前线程就是独占线程.线程重入。 else if (current == getExclusiveOwnerThread()) { //state值+1。犹豫都是同一线程进入,且持有了锁所以这里可以不用CAS机制加数量。 int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } //假如上面方法获取锁失败即返回false继续执行: acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) 先看addWaiter(): private Node addWaiter(Node mode) { //创建node节点。mode为模式当前设置的模式为Node.EXCLUSIVE排他锁; Node node = new Node(Thread.currentThread(), mode); // 快速入队。 Node pred = tail; if (pred != null) { node.prev = pred; //一切顺利没有其他线程入队此时用CAS入队。 if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } //不顺利有其他线程修改了队列的尾部node。那么就要循环入队 enq(node); return node; } private Node enq(final Node node) { for (;;) { Node t = tail; //当前队列为空 if (t == null) { //初始化一个节点 if (compareAndSetHead(new Node())) tail = head; } else { //无限尝试直到node加入队列 node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } } 然后是acquireQueued()方法: final boolean acquireQueued(final Node node, int arg) { boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); //如果node的前一个节点是头节点且再次尝试获取锁成功 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); } } private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) /* 如果前面的节点是signal即等待唤醒,那么当前节点可以被挂起。 */ return true; if (ws > 0) { /* * Predecessor was cancelled. Skip over predecessors and * indicate retry. 说明前面的线程已经被取消,一直循环将这些节点移出队列。 */ do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { /* * waitStatus must be 0 or PROPAGATE. Indicate that we * need a signal, but don't park yet. Caller will need to * retry to make sure it cannot acquire before parking. */ //设置前驱节点的状态为signal compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } return false; } private final boolean parkAndCheckInterrupt() { //挂起当前线程 LockSupport.park(this); //返回当前线程是否被中断 return Thread.interrupted(); } //取消线程 private void cancelAcquire(Node node) { if (node == null) return; node.thread = null; Node pred = node.prev; while (pred.waitStatus > 0) node.prev = pred = pred.prev; Node predNext = pred.next; node.waitStatus = Node.CANCELLED; if (node == tail && compareAndSetTail(node, pred)) { compareAndSetNext(pred, predNext, null); } else { int ws; if (pred != head && ((ws = pred.waitStatus) == Node.SIGNAL || (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && pred.thread != null) { Node next = node.next; if (next != null && next.waitStatus <= 0) compareAndSetNext(pred, predNext, next); } else { unparkSuccessor(node); } node.next = node; // help GC } }
总结:lock方法的所有步骤实现:
1、没有获得锁。
2、再次尝试获得锁。
3、获取锁失败就创建node加入队列。如果当前队列为空创建一个空节点为头尾,不为空即利用CAS机制无限循环直到加入队列为止。
4、判断当前线程是否为第二个节点,如果是,再次尝试获取锁(成功设置当前节点为头节点),如果不是判断是否需要挂起当前线程。
如果当前节点的前一个节点状态时singal时,挂起当前线程。如果不是signal,将当前节点前面的waitstatus>0(表明节点被中断)的所有节点移出队列。下次再进入这个方法的时候将前驱节点的值设置为singal。
所以所有线程都会阻塞在第四步。直到线程被唤醒。线程先离开必须是第二个节点,并且能够获取锁。