标签:gets mon 并发编程 for 设置 加锁 行锁 线程 sso
在并发编程中,除了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,才认为完全释放锁。释放以后,再唤醒挂起线程。
标签:gets mon 并发编程 for 设置 加锁 行锁 线程 sso
原文地址:https://www.cnblogs.com/sunshine-ground-poems/p/10340147.html