本文共 22708 字,大约阅读时间需要 75 分钟。
队列同步器(AQS)
队列同步器AbstractQueuedSynchronizer(以下简称同步器),是用来构建锁或者其他同步组件的基础框架,它使用了一个int成员变量表示同步状态,通过内置的FIFO队列来完成资源获取线程的排队工作,并发包的作者(Doug Lea)期望它能够成为实现大部分同步需求的基础。
队列同步器的基本结构
同步器依赖内部的同步队列(一个FIFO双向队列)来完成同步状态的管理。同步队列中的节点(Node)用来保存"获取同步状态失败的线程"引用、等待状态以及前驱和后继节点。
同步器包含了两个节点类型的引用,一个指向头节点,而另一个指向尾节点。
- public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer
- implements java.io.Serializable {
- ......
- private transient volatile Node head;
- private transient volatile Node tail;
- private volatile int state;
- ......
- static final class Node {
- volatile int waitStatus;
- volatile Node prev;
- volatile Node next;
- volatile Thread thread;
- ......
- }
- ......
- }
注:Node类型的prev、next属性以及AbstractQueuedSynchronizer类型的head 、tail属性都设置为volatile,保证可见性。
自定义同步组件的设计思路
同步器的主要使用方式是继承,子类通过继承同步器并实现它的抽象方法来管理同步状态,在抽象方法的实现过程中免不了要对同步状态进行更改,这时就需要使用同步器提供的3个方法(getState()、setState(int newState)和compareAndSetState(int expect,int update))来进行操作,因为它们能够保证状态的改变是安全的。
子类推荐被定义为自定义同步组件的静态内部类,同步器自身没有实现任何同步接口,它仅仅是定义了若干同步状态获取和释放的方法来供自定义同步组件使用,同步器既可以支持独占式地获取同步状态,也可以支持共享式地获取同步状态,这样就可以方便实现不同类型的同步组件(ReentrantLock、ReentrantReadWriteLock和CountDownLatch等)。
同步器是实现锁(也可以是任意同步组件)的关键,在锁的实现中聚合(组合)同步器,利用同步器实现锁的语义。可以这样理解二者之间的关系:锁是面向使用者的,它定义了使用者与锁交互的接口(比如可以允许两个线程并行访问),隐藏了实现细节;同步器面向的是锁的实现者,它简化了锁的实现方式,屏蔽了同步状态管理、线程的排队、等待与唤醒等底层操作。锁和同步器很好地隔离了使用者和实现者所需关注的领域。
同步器的设计是基于模板方法模式的,也就是说,使用者需要继承同步器并重写指定的方法,随后将同步器组合在自定义同步组件的实现中,并调用同步器提供的模板方法,而这些模板方法将会调用使用者重写的方法。
重写同步器指定的方法时,需要使用同步器提供的如下3个方法来访问或修改同步状态。
getState():获取当前同步状态。
setState(int newState):设置当前同步状态。
compareAndSetState(int expect,int update):使用CAS设置当前状态,该方法能够保证状态设置的原子性。
独占式同步组件的设计
可重写的方法
-
-
-
- protected boolean tryAcquire(int arg)
-
-
-
- protected boolean tryRelease(int arg)
-
-
-
- protected boolean isHeldExclusively()
同步器提供的模板方法
-
-
-
- public final void acquire(int arg)
-
-
-
- public final void acquireInterruptibly(int arg)
-
-
-
-
- public final boolean release(int arg)
acquire(int arg)模板方法
通过调用同步器的acquire(int arg)方法可以获取同步状态。该方法对中断不敏感,也就是说,由于线程获取同步状态失败后进入同步队列中,后续对线程进行中断操作时,线程不会从同步队列中移除。
- public final void acquire(int arg) {
- if (!tryAcquire(arg) &&
- acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
- selfInterrupt();
- }
独占式同步状态获取流程
主要逻辑:首先调用自定义同步器实现的tryAcquire(int arg)方法,该方法保证线程安全的获取同步状态,如果同步状态获取失败,则构造同步节点(独占式Node.EXCLUSIVE,同一时刻只能有一个线程成功获取同步状态)并通过addWaiter(Node node)方法将该节点加入到同步队列的尾部,最后调用acquireQueued(Node node,int arg)方法,使得该节点以“死循环”的方式获取同步状态。
将节点加入同步队列
当前线程获取同步状态失败时,同步器会将当前线程、等待状态等信息构造成为一个节点(Node)并将其加入同步队列,同时会阻塞当前线程。
试想一下,当一个线程成功地获取了同步状态(或者锁),其他线程将无法获取到同步状态,转而被构造成为节点并加入到同步队列中,而这个加入队列的过程必须要保证线程安全。
因此,同步器提供了一个基于CAS的设置尾节点的方法:compareAndSetTail(Nodeexpect,Nodeupdate),它需要传递当前线程“认为”的尾节点和当前节点,只有设置成功后,当前节点才正式与之前的尾节点建立关联。
-
- private Node addWaiter(Node mode) {
- Node node = new Node(Thread.currentThread(), mode);
-
-
- Node pred = tail;
- if (pred != null) {
- node.prev = pred;
- if (compareAndSetTail(pred, node)) {
-
-
- pred.next = node;
- return 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.prev = t;
- if (compareAndSetTail(t, node)) {
- t.next = node;
- return t;
- }
- }
- }
- }
在enq(final Node node)方法中,同步器通过“死循环”来保证节点的正确添加,在“死循环”中只有通过CAS将节点设置成为尾节点之后,当前线程才能从该方法返回,否则,当前线程不断地尝试设置。可以看出,enq(final Node node)方法将并发添加节点的请求通过CAS变得“串行化”了。
串行化的优点
如果通过加锁同步的方式添加节点,线程必须获取锁后才能添加尾节点,那么必然会导致其他线程等待加锁而阻塞,获取锁的线程释放锁后阻塞的线程又会被唤醒,而线程的阻塞和唤醒需要依赖于系统内核完成,因此程序的执行需要从用户态切换到核心态,而这样的切换是非常耗时的操作。如果我们通过”循环CAS“来添加节点的话,所有线程都不会被阻塞,而是不断失败重试,线程不需要进行锁同步,不仅消除了线程阻塞唤醒的开销而且消除了加锁解锁的时间开销。但是循环CAS也有其缺点,循环CAS通过不断尝试来添加节点,如果说CAS操作失败那么将会占用处理器资源。
节点的自旋
节点进入同步队列之后,就进入了一个自旋的过程,每个节点(或者说是线程)都在自省地观察,当条件满足,获取到了同步状态,就可以从这个自旋过程中退出,否则依旧留在这个自旋过程中。
- 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;
- 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)
-
-
- return true;
- if (ws > 0) {
-
- do {
- node.prev = pred = pred.prev;
- } while (pred.waitStatus > 0);
- pred.next = node;
- } else {
-
-
- compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
- }
- return false;
- }
-
- private final boolean parkAndCheckInterrupt() {
- LockSupport.park(this);
- return Thread.interrupted();
- }
可以看到节点和节点之间在循环检查的过程中基本不相互通信,而是简单地判断自己的前驱是否为头节点,这样就使得节点的释
放规则符合FIFO。并且也便于对过早通知的处理(过早通知是指:前驱节点不是头节点的线程由于
中断而被
唤醒)。
当同步状态获取成功之后,当前线程从acquire(int arg)方法返回,如果对于锁这种并发组件而言,代表着当前线程获取了锁。
设置首节点
同步队列遵循FIFO,首节点是获取同步状态成功的节点,首节点的线程在释放同步状态时,将会唤醒后续节点,而后续节点将会在获取同步状态成功时将自己设置为首节点。
设置首节点是由获取同步状态成功的线程来完成的,由于只有一个线程能够成功的获取到同步状态,因此设置头节点的方法并不需要使用CAS来保证,它只需要将首节点设置成为原首节点后继节点,并断开首节点的next引用即可。
释放同步状态
当前线程获取同步状态并执行了相应逻辑之后,就需要释放同步状态,使得后续节点能够继续获取同步状态。通过调用同步器的release(int arg)方法可以释放同步状态,该方法在释放了同步状态之后,会"唤醒"其后继节点(进而使后继节点重新尝试获取同步状态)。
- public final boolean release(int arg) {
- if (tryRelease(arg)) {
- Node h = head;
- if (h != null && h.waitStatus != 0)
- unparkSuccessor(h);
- return true;
- }
- return false;
- }
-
- private void unparkSuccessor(Node node) {
- int ws = node.waitStatus;
- if (ws < 0)
- compareAndSetWaitStatus(node, ws, 0);
-
-
-
-
- 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);
- }
总结:在获取同步状态时,同步器维护一个同步队列,获取状态失败的线程都会被加入到队列中并在队列中进行自旋;移出队列
(或停止自旋)的条件是前驱节点为头节点且成功获取了同步状态。在释放同步状态时,同步器调用tryRelease(int arg)方法释放同步状态,然后唤醒头节点的后继节点。 独占锁(Mutex)
- import java.util.Collection;
- import java.util.concurrent.locks.AbstractQueuedSynchronizer;
-
- public class Mutex {
-
- private static class Sync extends AbstractQueuedSynchronizer {
-
- protected boolean isHeldExclusively() {
- return getState() == 1;
- }
-
- public boolean tryAcquire(int acquires) {
- if (compareAndSetState(0, 1)) {
- setExclusiveOwnerThread(Thread.currentThread());
- return true;
- }
- return false;
- }
-
- protected boolean tryRelease(int releases) {
- if (getState() == 0)
- throw new IllegalMonitorStateException();
- setExclusiveOwnerThread(null);
- setState(0);
- return true;
- }
- }
-
- private final Sync sync = new Sync();
-
-
- public Collection<Thread> getQueuedThreads(){
- return sync.getQueuedThreads();
- }
-
-
- public void lock() {
- sync.acquire(1);
- }
-
- public void unlock() {
- sync.release(1);
- }
- }
- import java.util.Collection;
- import java.util.Random;
-
- public class MutexTestSecond {
- private static Random r=new Random(47);
- private static int threadCount=10;
- private static Mutex mut=new Mutex();
- private static class Weight implements Runnable{
- String name;
- public Weight(String name){
- this.name=name;
- }
- @Override
- public void run() {
- mut.lock();
- System.out.println(name+"放苹果!");
- System.out.println(name+"重量:"+(r.nextInt(10)+3));
- System.out.println(name+"取苹果!");
- printQueuedThreads(mut.getQueuedThreads());
- mut.unlock();
- }
- }
- private static void printQueuedThreads(Collection<Thread> threads){
- System.out.print("等待队列中的线程:");
- for(Thread t:threads){
- System.out.print(t.getName()+" ");
- }
- System.out.println();
- }
- public static void main(String[] args) {
- Thread[] threads=new Thread[threadCount];
- for(int i=0;i<threadCount;i++){
- threads[i]=new Thread(new Weight("Weight-"+i),"Thread-"+i);
- }
- for(int i=0;i<threadCount;i++){
- threads[i].start();
- }
- }
- }
输出:
Weight-0放苹果!
Weight-0重量:11
Weight-0取苹果!
等待队列中的线程:Thread-3 Thread-2 Thread-1
Weight-6放苹果!
Weight-6重量:8
Weight-6取苹果!
等待队列中的线程:Thread-8 Thread-7 Thread-5 Thread-4 Thread-3 Thread-2 Thread-1
Weight-1放苹果!
Weight-1重量:6
Weight-1取苹果!
等待队列中的线程:Thread-9 Thread-8 Thread-7 Thread-5 Thread-4 Thread-3 Thread-2
Weight-2放苹果!
Weight-2重量:4
Weight-2取苹果!
等待队列中的线程:Thread-9 Thread-8 Thread-7 Thread-5 Thread-4 Thread-3
Weight-3放苹果!
Weight-3重量:4
Weight-3取苹果!
等待队列中的线程:Thread-9 Thread-8 Thread-7 Thread-5 Thread-4
Weight-4放苹果!
Weight-4重量:12
Weight-4取苹果!
等待队列中的线程:Thread-9 Thread-8 Thread-7 Thread-5
Weight-5放苹果!
Weight-5重量:11
Weight-5取苹果!
等待队列中的线程:Thread-9 Thread-8 Thread-7
Weight-7放苹果!
Weight-7重量:3
Weight-7取苹果!
等待队列中的线程:Thread-9 Thread-8
Weight-8放苹果!
Weight-8重量:5
Weight-8取苹果!
等待队列中的线程:Thread-9
Weight-9放苹果!
Weight-9重量:10
Weight-9取苹果!
等待队列中的线程:
从输出中可以看出,我们的独占锁Mutex,保证了秤的独占使用。
重入锁
重入锁ReentrantLock,顾名思义,就是支持重进入的锁,它表示该锁能够支持一个线程对资源的重复加锁。除此之外,该锁的还支持获取锁时的公平和非公平性选择。
对于独占锁(Mutex),考虑如下场景:当一个线程调用Mutex的lock()方法获取锁之后,如果再次调用lock()方法,则该线程将会被自己所阻塞,原因是Mutex在实现tryAcquire(int acquires)方法时没有考虑占有锁的线程再次获取锁的场景,而在调用tryAcquire(int acquires)方法时返回了false,导致该线程被阻塞。简单地说,Mutex是一个不支持重进入的锁。
synchronized关键字隐式的支持重进入,比如一个synchronized修饰的递归方法,在方法执行时,执行线程在获取了锁之后仍能连续多次地获得该锁,而不像Mutex由于获取了锁,而在下一次获取锁时出现阻塞自己的情况。
ReentrantLock虽然没能像synchronized关键字一样支持隐式的重进入,但是在调用lock()方法时,已经获取到锁的线程,能够再次调用lock()方法获取锁而不被阻塞。
可重入的实现
重进入是指任意线程在获取到锁之后能够再次获取该锁而不会被锁所阻塞,该特性的实现需要解决以下两个问题。
1)线程再次获取锁。锁需要去识别获取锁的线程是否为当前占据锁的线程,如果是,则再次成功获取。
2)锁的最终释放。线程重复n次获取了锁,随后在第n次释放该锁后,其他线程能够获取到该锁。锁的最终释放要求锁对于获取进行计数自增,计数表示当前锁被重复获取的次数,而锁被释放时,计数自减,当计数等于0时表示锁已经成功释放。
ReentrantLock是通过组合自定义同步器来实现锁的获取与释放。我们以非公平锁为例:
- public class ReentrantLock implements Lock, java.io.Serializable {
- private final Sync sync;
-
- ......
- abstract static class Sync extends AbstractQueuedSynchronizer {
- private static final long serialVersionUID = -5179523762034025860L;
-
- abstract void lock();
-
- 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)
- 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;
- }
- ......
- }
- static final class NonfairSync extends Sync {
- private static final long serialVersionUID = 7316153563782823691L;
-
-
- final void lock() {
- if (compareAndSetState(0, 1))
- setExclusiveOwnerThread(Thread.currentThread());
- else
- acquire(1);
- }
-
- protected final boolean tryAcquire(int acquires) {
- return nonfairTryAcquire(acquires);
- }
- }
- ......
- public void lock() {
- sync.lock();
- }
- public void unlock() {
- sync.release(1);
- }
- ......
- }
- import java.util.Random;
- import java.util.concurrent.locks.ReentrantLock;
-
- public class ReentrantLockTest {
- private static Random r=new Random(47);
- private static int threadCount=10;
- private static ReentrantLock mut=new ReentrantLock();
- private static class Weight implements Runnable{
- String name;
- public Weight(String name){
- this.name=name;
- }
- @Override
- public void run() {
- mut.lock();
- System.out.println(name+"放苹果!");
- System.out.println(name+"重量:"+(r.nextInt(10)+3));
- System.out.println(name+"取苹果!");
- if(r.nextInt()%2==0){run();}
- mut.unlock();
- }
- }
- public static void main(String[] args) throws InterruptedException {
- Thread[] threads=new Thread[threadCount];
- for(int i=0;i<threadCount;i++){
- threads[i]=new Thread(new Weight("Weight-"+i),"Thread-"+i);
- }
- for(int i=0;i<threadCount;i++){
- threads[i].start();
- Thread.sleep(10);
- }
- }
- }
输出:
Weight-0放苹果!
Weight-0重量:11
Weight-0取苹果!
Weight-0放苹果!
Weight-0重量:6
Weight-0取苹果!
Weight-0放苹果!
Weight-0重量:4
Weight-0取苹果!
Weight-1放苹果!
Weight-1重量:11
Weight-1取苹果!
Weight-2放苹果!
Weight-2重量:5
Weight-2取苹果!
Weight-2放苹果!
Weight-2重量:11
Weight-2取苹果!
Weight-2放苹果!
Weight-2重量:4
Weight-2取苹果!
Weight-3放苹果!
Weight-3重量:12
Weight-3取苹果!
Weight-3放苹果!
Weight-3重量:11
Weight-3取苹果!
Weight-3放苹果!
Weight-3重量:3
Weight-3取苹果!
Weight-3放苹果!
Weight-3重量:9
Weight-3取苹果!
Weight-5放苹果!
Weight-5重量:4
Weight-5取苹果!
Weight-7放苹果!
Weight-7重量:7
Weight-7取苹果!
Weight-8放苹果!
Weight-8重量:9
Weight-8取苹果!
Weight-6放苹果!
Weight-6重量:3
Weight-6取苹果!
Weight-4放苹果!
Weight-4重量:7
Weight-4取苹果!
Weight-4放苹果!
Weight-4重量:3
Weight-4取苹果!
Weight-9放苹果!
Weight-9重量:5
Weight-9取苹果!
Weight-9放苹果!
Weight-9重量:6
Weight-9取苹果!
Weight-9放苹果!
Weight-9重量:7
Weight-9取苹果!
从输出中,可以看出可重入特性。如果,我们将可重入锁换成独占锁Mutex程序将会阻塞,不具有可重入性。
此外,我们还发现,线程的执行是乱序的(从线程名称的角度看),即与start()方法调用顺序不一致。这是为什么呢?
原来重入锁ReentrantLock默认采用非公平实现?那好,我们将可重入锁设置为公平锁:
- private static ReentrantLock mut=new ReentrantLock(true);
输出:
Weight-0放苹果!
Weight-0重量:11
Weight-0取苹果!
Weight-0放苹果!
Weight-0重量:6
Weight-0取苹果!
Weight-0放苹果!
Weight-0重量:4
Weight-0取苹果!
Weight-1放苹果!
Weight-1重量:11
Weight-1取苹果!
Weight-2放苹果!
Weight-2重量:5
Weight-2取苹果!
Weight-2放苹果!
Weight-2重量:11
Weight-2取苹果!
Weight-2放苹果!
Weight-2重量:4
Weight-2取苹果!
Weight-3放苹果!
Weight-3重量:12
Weight-3取苹果!
Weight-3放苹果!
Weight-3重量:11
Weight-3取苹果!
Weight-3放苹果!
Weight-3重量:3
Weight-3取苹果!
Weight-3放苹果!
Weight-3重量:9
Weight-3取苹果!
Weight-7放苹果!
Weight-7重量:4
Weight-7取苹果!
Weight-6放苹果!
Weight-6重量:7
Weight-6取苹果!
Weight-4放苹果!
Weight-4重量:9
Weight-4取苹果!
Weight-5放苹果!
Weight-5重量:3
Weight-5取苹果!
Weight-8放苹果!
Weight-8重量:7
Weight-8取苹果!
Weight-8放苹果!
Weight-8重量:3
Weight-8取苹果!
Weight-9放苹果!
Weight-9重量:5
Weight-9取苹果!
Weight-9放苹果!
Weight-9重量:6
Weight-9取苹果!
Weight-9放苹果!
Weight-9重量:7
Weight-9取苹果!
从输出中我们看到,线程的执行顺序与对应start()方法被调用的顺序依然不一样,说好的公平锁呢?
原因分析:start()语句调用的顺序与线程进入Runnable状态的顺序不一定一致,也就是说先调用start()语句所对应的线程不一定先进入Runnable状态,即使先进入Runnable状态也不一定先分得处理器开始执行。
公平性与否是针对获取锁而言的,如果一个锁是公平的,那么锁的获取顺序就应该符合请求的绝对时间顺序,也就是FIFO。
个人理解,如有偏颇,还望指正!!
非公平性的实现
- static final class NonfairSync extends Sync {
- private static final long serialVersionUID = 7316153563782823691L;
-
-
- final void lock() {
- if (compareAndSetState(0, 1))
- setExclusiveOwnerThread(Thread.currentThread());
- else
- acquire(1);
- }
-
- protected final boolean tryAcquire(int acquires) {
- return nonfairTryAcquire(acquires);
- }
- }
非公平性实例,如果Thread-1拥有锁,Thread-2和Thread-3在同步队列中,当Thread-1释放锁后会唤醒Thread-2,但是如果此时Thread-1重新申请锁,可能依然是Thread-1获取到锁。甚至这时候Thread-4也申请锁,Thread-4也可能比Thread-2先获取锁。
非公平锁可能使得线程“饥饿”。当一个线程请求锁时,只要获取了同步状态即成功获取锁。在这个前提下,刚释放锁的线程再次获取同步状态的几率会非常大,使得其他线程只能在同步队列中等待。
公平性的实现
- static final class FairSync extends Sync {
- private static final long serialVersionUID = -3000897897090466540L;
-
- final void lock() {
- acquire(1);
- }
-
-
- protected final boolean tryAcquire(int acquires) {
- final Thread current = Thread.currentThread();
- int c = getState();
-
- if (c == 0) {
- if (!hasQueuedPredecessors() &&<span><span class="comment">
- 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;
- }
- }
公平锁与非公平锁的比较
公平性与否是针对获取锁而言的,如果一个锁是公平的,那么锁的获取顺序就应该符合请求的绝对时间顺序,也就是FIFO。
公平性锁每次都是从同步队列中的第一个节点获取到锁,而非公平性锁出现了一个线程连续获取锁的情况。
非公平性锁可能使线程“饥饿”,当一个线程请求锁时,只要获取了同步状态即成功获取锁。在这个前提下,刚释放锁的线程再次获取同步状态的几率会非常大,使得其他线程只能在同步队列中等待。
非公平锁可能使线程“饥饿”,为什么它又被设定成默认的实现呢?非公平性锁模式下线程上下文切换的次数少,因此其性能开销更小。公平性锁保证了锁的获取按照FIFO原则,而代价是进行大量的线程切换。非公平性锁虽然可能造成线程“饥饿”,但极少的线程切换,保证了其更大的吞吐量。
共享式同步组件设计
可重写的方法
-
-
-
- protected int tryAcquireShared(int arg)
-
-
-
-
- protected boolean tryReleaseShared(int arg)
同步器提供的模板方法
-
-
-
- public final void acquireShared(int arg)
-
- <span style="font-size:14px;"><span style="font-size:14px;"></span></span><pre name="code" class="java">
-
- public final void acquireInterruptibly(int arg)
/**Releases in shared mode. Implemented by unblocking one or more * threads if {@link #tryReleaseShared} returns true.*/ //共享式释放同步状态 public final boolean releaseShared(int arg)
共享式获取与独占式获取最主要的区别在于同一时刻能否有多个线程同时获取到同步状态。以文件的读写为例,如果一个程序在对文件进行读操作,那么这一时刻对于该文件的写操作均被阻塞,而读操作能够同时进行。写操作要求对资源的独占式访问,而读操作可以是共享式访问。
获取同步状态
调用同步器的acquireShared(int arg)方法可以共享式地获取同步状态。
- public final void acquireShared(int arg) {
- if (tryAcquireShared(arg) < 0)
- doAcquireShared(arg);
- }
在acquireShared(int arg)方法中,同步器调用tryAcquireShared(int arg)方法尝试获取同步状态,tryAcquireShared(int arg)方法返回值为int类型,当返回值大于等于0时,表示能够获取到同步状态。因此,在共享式获取的自旋过程中,成功获取到同步状态并退出自旋的条件就是tryAcquireShared(int arg)方法返回值大于等于0。
在doAcquireShared(int arg)方法的自旋过程中,如果当前节点的前驱为头节点时,尝试获取同步状态,如果返回值大于等于0,表示该次获取同步状态成功并从自旋过程中退出。
释放同步状态
与独占式一样,共享式获取也需要释放同步状态,通过调用releaseShared(int arg)方法可以释放同步状态。
- public final boolean releaseShared(int arg) {
- if (tryReleaseShared(arg)) {
- doReleaseShared();
- return true;
- }
- return false;
- }
该方法在释放同步状态之后,将会唤醒后续处于等待状态的节点。对于能够支持多个线程同时访问的并发组件(比Semaphore),它和独占式主要区别在于tryReleaseShared(int arg)方法必须确保同步状态(或者资源数)线程安全释放,一般是通过循环和CAS来保证的,因为释放同步状态的操作会同时来自多个线程。
CountDownLatch
- public class CountDownLatch {
-
- private static final class Sync extends AbstractQueuedSynchronizer {
- private static final long serialVersionUID = 4982264981922014374L;
-
- Sync(int count) {
- setState(count);
- }
-
- int getCount() {
- return getState();
- }
-
- protected int tryAcquireShared(int acquires) {
- return (getState() == 0) ? 1 : -1;
- }
-
- protected boolean tryReleaseShared(int releases) {
-
- for (;;) {
- int c = getState();
- if (c == 0)
- return false;
- int nextc = c-1;
- if (compareAndSetState(c, nextc))
- return nextc == 0;
- }
- }
- }
-
- private final Sync sync;
-
- public CountDownLatch(int count) {
- if (count < 0) throw new IllegalArgumentException("count < 0");
- this.sync = new Sync(count);
- }
-
-
-
- public void await() throws InterruptedException {
- sync.acquireSharedInterruptibly(1);
- }
-
- public boolean await(long timeout, TimeUnit unit)
- throws InterruptedException {
- return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
- }
- public void countDown() {
- sync.releaseShared(1);
- }
-
- public long getCount() {
- return sync.getCount();
- }
-
- public String toString() {
- return super.toString() + "[Count = " + sync.getCount() + "]";
- }
- }
独占式超时获取同步状态
Lock接口
锁是用来控制多个线程访问共享资源的方式,一般来说,一个锁能够防止多个线程同时访问共享资源(但是有些锁可以允许多个线程并发的访问共享资源,比如读写锁)。
在Lock接口出现之前,程序是靠synchronized关键字实现锁功能的,而 5之后,并发包中新增了Lock接口(以及相关实现类)用来实现锁功能,它提供了与synchronized关键字类似的同步功能,只是在使用时需要显式地获取和释放锁。虽然它缺少了(通过synchronized块或者方法所提供的)隐式获取释放锁的便捷性,但是却拥有了锁获取与释放的可操作性、可中断的获取锁以及超时获取锁等多种synchronized关键字所不具备的同步特性。
使用synchronized关键字将会隐式地获取锁,但是它将锁的获取和释放固化了,也就是先获取再释放。当然,这种方式简化了同步的管理,可是扩展性没有显示的锁获取和释放来的好。例如,针对一个场景,手把手进行锁获取和释放,先获得锁A,然后再获取锁B,当锁B获得后,释放锁A同时获取锁C,当锁C获得后,再释放B同时获取锁D,以此类推。这种场景下,synchronized关键字就不那么容易实现了,而使用Lock却容易许多。
Lock的使用方式
- Lock lock = new ReentrantLock();
- lock.lock();
- try {
- 。。。。。。
- } finally {
- lock.unlock();
- }
在finally块中释放锁,目的是保证在获取到锁之后,最终能够被释放。 不要将获取锁的过程写在try块中,因为如果在获取锁(自定义锁的实现)时发生了异常,异常抛出的同时,也会导致锁无故释放。 Lock接口提供的新特性
Lock接口
- public interface Lock {
-
- void lock();
-
- void lockInterruptibly() throws InterruptedException;
-
- boolean tryLock();
-
- boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
-
- void unlock();
-
- Condition newCondition();
- }
Lock接口的实现
Lock接口的实现基本都是通过组合了一个队列同步器(AbstractQueuedSynchronizer)的子类来完成线程访问控制的。
例如,ReentrantLock(重入锁)。
说在最后:关于可响应中断和超时等待特性,文中基本略过,详情可参看《Java并发编程的艺术》和JDK源码。 参考:
JDK 1.7源码
《Java并发编程的艺术》
《Java并发编程实践》