当前位置: 移动技术网 > IT编程>开发语言>Java > ReentrantLock实现原理

ReentrantLock实现原理

2019年01月31日  | 移动技术网IT编程  | 我要评论

  在并发编程中,除了synchronized关键字,java并发包中java.util.concurrent.locks中的reentrantlock和reentrantreadwritelock也是常用的锁实现。本篇从源码方面,分析一下重入锁reentrantlock的原理。

  先说一下什么的重入锁:某个线程获得锁以后,还可以多次重复获得锁,不会自己阻塞自己。

  reentrantlock基于抽象类abstractqueuedsynchronizer(以下简称aqs)实现。

  看源码:

  首先从构造器上可以看出,reentrantlock有公平锁和非公平锁两种机制。

//默认非公平锁
public reentrantlock() { sync = new nonfairsync(); } public reentrantlock(boolean fair) { sync = fair ? new fairsync() : new nonfairsync(); }

  

  先简要说明一下公平锁和非公平锁的区别,然后在分析两者的不同实现方式。

  公平锁:多个线程之间讲究先来后到。类似于排队,后面来的线程依次排在队列最后。

  非公平锁:进行锁的争抢。抢到就执行,没抢到就阻塞。等待获得锁的线程释放后,再参与竞争。

  所以通常使用非公平锁。其效率比公平锁高。

获取锁

公平锁

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

public final void acquire(int arg) {
        if (!tryacquire(arg) &&
            acquirequeued(addwaiter(node.exclusive), arg))
            selfinterrupt();
    }

  第一步tryacquire(arg)尝试加锁,由fairsync实现,具体代码如下:

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;
        }
  • 获取当前线程
  • 获取aqs中的state。如果state为0,表示此时没有线程获得锁。  
  • 在if判断中,先要判断aqs的node队列是否为空。如果不是空的,就需要排队。此时不获取锁。
  • 尝试使用cas算法,将state更新为1。更新成功,获取锁,将此时的线程设置为独占线程exclusiveownerthread。返回true。
  • 如果state不为0,表示已经有线程获得了锁。所以要判断获得锁的线程(独占线程)是否为当前线程。
  • 如果是,说明是重入情况。将state增加1。返回true。
  • 走到最后一步,就是没有获得锁了。返回false;

  继续上面的步骤,如果获取锁失败,先执行addwaiter(node.exclusive),将当前线程写入队列

private node addwaiter(node mode) {
        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.prev = pred;
            if (compareandsettail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }
  • 封装一个新节点node
  • 判断链表尾是否为空,不是就把新节点node‘写入最后
  • ’链表尾为空,则用enq(node)写入最后。

  写入队列以后,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);
        }
    }
  • 在循环中,如果node的上一个是头节点,则再尝试获取锁。成功就结束循环,返回false
  • 不是头节点,就根据上一个节点的waitstatus,判断是否需要挂起当前线程。waitstatus用来记录节点状态,如节点取消,节点等待等。
  • 判断需要挂起,则使用parkandcheckinterrupt()方法,挂起线程。具体使用locksupport.park(this)挂起线程。
  • 如果在这里的第一步就获取锁成功了,就可以取消此节点的获取锁操作了。

非公平锁

  非公平锁在锁的获取策略上有差异。

final void lock() {
            if (compareandsetstate(0, 1))
                setexclusiveownerthread(thread.currentthread());
            else
                acquire(1);
        }

 protected final boolean tryacquire(int acquires) {
            return nonfairtryacquire(acquires);
        }
  • 非公平锁先直接尝试使用cas算法更新state,获取锁
  • 更新失败以后,在尝试获取锁
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;
        }

  与公平锁相比,非公平锁尝试获取锁的过程中,无需判断队列中是否存在其他线程。

释放锁

  公平锁和非公平锁释放锁的步骤都一样

  

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;
    }
//更新state
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;
        }

  值得注意的是,因为是重入锁的关系,在tryrelease()方法中,需要将state更新为0,才认为完全释放锁。释放以后,再唤醒挂起线程。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网