在并发编程中,除了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; }
继续上面的步骤,如果获取锁失败,先执行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; }
写入队列以后,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); } }
非公平锁
非公平锁在锁的获取策略上有差异。
final void lock() { if (compareandsetstate(0, 1)) setexclusiveownerthread(thread.currentthread()); else acquire(1); } protected final boolean tryacquire(int acquires) { return nonfairtryacquire(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; }
与公平锁相比,非公平锁尝试获取锁的过程中,无需判断队列中是否存在其他线程。
释放锁
公平锁和非公平锁释放锁的步骤都一样
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,才认为完全释放锁。释放以后,再唤醒挂起线程。
如对本文有疑问, 点击进行留言回复!!
【奥鹏作业答案库网】大工20春《应用统计》在线作业1【奥鹏作业答案】
网友评论