JUC之ReentrantLock源码阅读

ReentrantLock是juc包里的一种重要的锁。可重入锁,顾名思义,就是一个线程可以重复进入该锁所保护的临界资源。下面通过源码阅读,来一步一步看是怎么实现的。

uml图

ReentrantLock

ReentrantLock实现了Lock和serializable接口,同时其主要操作委托给其内部类Sync来执行。Sync有两个子类FairSync和NonfairSync,即公平锁和非公平锁。Sync同时又继承了AbstractQueuedSynchronizer,java中的一个重要的类,简称AQS。该类主要维护一个双向的链表,表的Node为等待获取锁的线程。所有新入队的Node都在表为,即tail所在的位置。所有自行的线程,都放在表头,即head所指的位置。

一个例子进入学习

import java.util.concurrent.locks.ReentrantLock;

public class TestReenterLock implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();

    public static int i = 0;

    @Override
    public void run() {
        for (int j = 0; j < 100000; j++) {
            lock.lock();
            try {
                i++;
            }finally {
                lock.unlock();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestReenterLock instance = new TestReenterLock();
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
}

代码例子中,操作临界资源前,通过lock.lock()方法获取锁,操作完成后,通过unlock方法释放锁。
接下来看lock方法的实现。

lock方法

ReentrantLock中的lock方法很简单。

public void lock() {
        sync.lock();
    }

其委托给sync的lock方法。
由上图可以看到,Sync是一个继承至AQS的类abstract static class Sync extends AbstractQueuedSynchronizer,其为一个抽象的类。有两个子类,FairSync和NonfairSync,即公平锁和非公平锁。
首先看非公平锁,也是默认的实现。

  final void lock() {
            //尝试获取锁,通过修改AQS的状态
            if (compareAndSetState(0, 1))
            //获取成功,将当前的线程置为独占的
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

compareAndSetState为AQS里的方法,源码实现如下:

protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

这里用了unsafe的相关操作。compareAndSwapInt有四个参数,分别是需要修改的对象,对象的内存地址,期望的原始值和更新后的值。
回到lock方法,当其没有获取到资源时,则调用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();
          //当前状态为0,没有线程持有锁,可以获取锁了
            if (c == 0) {
              // 修改状态,获取资源
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
          //若已有线程持有锁,则判断是否是当前线程持有的,若是,则修改状态,在原有状态上+1
          //该处体现了重入锁的概念了。
            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;
        }

上面的一段代码体现了重入锁重入的概念。即如果发现是当前线程持有了锁,则线程再一次获取锁的时候,再状态上加一,释放的时候将state减1,所以,当对一个线程多次获取锁时,需要对应次数的unlock操作,如若不然,可能会使其他线程一直无法获取锁。如下:

lock.lock();
lock.lock();
try{
业务处理代码
}finally{
 lock.unlock();
 lock.unlock();
}

acquireQueued(addWaiter(Node.EXCLUSIVE), arg))源码如下:
addWaiter如下:

 private Node addWaiter(Node mode) {
    //创建一个node
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        
        Node pred = tail;
        if (pred != null) {
            //将当前的node的前驱设置为队列的尾部
            node.prev = pred;
            //设置tail指向当前node
            if (compareAndSetTail(pred, node)) {
              //设置原tail指向的节点的next指向当前node,形成一个双向链表。
                pred.next = node;
                //返回当前节点
                return node;
            }
        }
      //若队尾为空
        enq(node);
        return node;
    }
    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

将自己的node放到等待队列尾部。
acquireQueued的代码如下:

    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
              //获取node的前驱节点
                final Node p = node.predecessor();
              //若前驱节点是队列的头节点,且能获取到资源,则将当前节点设置为头节点,并返回,退出循环。
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
              //设置当前节点的等待状态,并调用LockSupport.park(this)方法,阻塞当前线程。
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

以上是非公平锁的代码,非公平体现在何处呢?
非公平体现在,当前线程执行完之后,唤醒队列头的等待队列时,如果有新线程来了,正好获取到资源了,则会把该资源放到队头,进行执行,而不是遵循着先到先执行的原则。公平锁就是按照队列头开始,一个节点一个节点的往下执行,先到先执行的意思在里边。

公平锁对应的代码如下:

 final void lock() {
            acquire(1);
        }

相对于非公平锁来说,少了获取资源的判断,这样就不会有线程插队,而是老老实实的唤醒队头的线程。

unlock方法

unlock也是委托给sync的unlock方法。unlock没有公不公平这一说。
unlock代码如下:

 public void unlock() {
        sync.release(1);
    }
public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

tryRelease方法是试图释放锁。代码如下:

  protected final boolean tryRelease(int releases) {
          //同一线程多次获取锁,在释放的时候,需要多次unlock,体现在这个地方
            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;
        }

Node的waitStatus 有如下状态值:

  /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1;
        /** waitStatus value to indicate successor's thread needs unparking */
        static final int SIGNAL    = -1;
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2;
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3;
private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }

以上代码大意就是从队尾开始向前遍历,找到离队头最近的一个没有被cannel的线程,调用unpark方法唤醒该等待队列。

到此,ReentrantLock差不多读完了。

你可能感兴趣的:(JUC之ReentrantLock源码阅读)