码迷,mamicode.com
首页 > 其他好文 > 详细

4.JUC之AQS框架

时间:2017-09-06 12:58:00      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:ansi   map   ack   sse   private   add   相关   共享模式   构造方法   

原文链接:http://blog.csdn.net/zteny/article/details/54919765

一、简介

1.AQS

AQS是AbstractQueuedSynchronizer的简写,直白的翻译:抽象队列同步器,jdk1.5后出现

 

Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues. This class is designed to be a useful basis for most kinds of synchronizers that rely on a single atomic intvalue to represent state. Subclasses must define the protected methods that change this state, and which define what that state means in terms of this object being acquired orreleased. Given these, the other methods in this class carry out all queuing and blocking mechanics. Subclasses can maintain other state fields, but only the atomically updated int value manipulated using methods getState, setState and compareAndSetState is tracked with respect to synchronization. ——Java docs

翻开源码,首先是一大段的注释,然后可以看开AQS继承自AbstractOwnableSynchronizer。当你翻开AbstractOwnableSynchronizer时,还是先看到小段的说注释。

A synchronizer that may be exclusively owned by a thread. This class provides a basis for creating locks and related synchronizers that may entail a notion of ownership. The AbstractOwnableSynchronizer class itself does not manage or use this information. However, subclasses and tools may use appropriately maintained values to help control and monitor access and provide diagnostics. ——Java docs

 

2.AOS

  生自java1.6,可以由线程以独占的方式拥有的同步器。此类为创建锁和相关同步器(伴随着所有权的概念)提供了基础。

  AbstractOwnableSynchronizer类本身不管理或使用此信息。但是,子类和工具可以使用适当维护的值帮助控制和监视访问以及提供诊断

  简而言之,AOS输出的是一种概念,是一种创建独占锁同步器所有权的概念。他自身并没有规范所有权的管理方式,更没有用到这些信息(所有权的信息)。不过呢,可以帮其子类维护所有者信息。

  可能上面的话仍然不够清晰,下面看看源码。

  AOS提供两个方法一个字段,外带一个空构造方法(可无视)

 1 /**
 2  * The current owner of exclusive mode synchronization.
 3  */
 4 private transient Thread exclusiveOwnerThread; // transient表示该字段不需要序列化,因为AOS实现了Serializable
 5 
 6 protected final void setExclusiveOwnerThread(Thread thread) {
 7     exclusiveOwnerThread = thread;
 8 }
 9 
10 protected final Thread getExclusiveOwnerThread() {
11     return exclusiveOwnerThread;
12 }

  这下明白了吧,就是AOS只维护一个东西------当前谁持有独占式同步器。因此咱们可以当他不存在,继续回到AQS

 

二、作用

  从Java Docs的注释可以知道,AQS是一个框架,一个提供锁或同步器依赖于FIFO等待队列所必要的 “基础设施”的框架,Doug  Lea之所以写个抽象类的目的是为了简化我们实现同步器的工作

也就是说:

  提供一个基于FIFO等待队列,可以用于构建锁或其他同步装置的基础框架。意在能够实现大部分同步需求的基础

  AQS默认提供了独占式和共享式两种模式,JDK对应的实现有ReentrantLock 和 ReentrantReadWriteLock。即除了提供acquire方法之外,还提供了acquireShare。带shared都是共享模式相关操作,默认则是独占模式。

  AQS到底提供了哪些便利呢:

  1.管理状态

  2.实现了线程按安全的CLH队列

  3.实现了同步器公共方法

  4.ConditionObject

 

三、原理

  AQS自身就是一个Wait Queue,CLH lock  queue的变种,CLH队列通常用于自旋锁。

  The wait queue is a variant of a “CLH” (Craig, Landin, and Hagersten) lock queue. CLH locks are normally used for spinlocks. We instead use them for blocking synchronizers, but use the same basic tactic of holding some of the control information about a thread in the predecessor of its node.

  我们知道Queue的底层实现是一个链表结构,我们也知道它可以是单链表,也可以是双链表。AQS实现的是一个双链表结构。即每个节点都存储了前驱和后继两个指针,而且Head节点是dummy节点。入队则tail前驱一个节点,再把新节点接入,然后接入tail节点。

 

  AQS完全通过CAS解决多线程安全问题,即通过Unsafe完成的。具体可以自行阅读AQS源码,在最后几个方法,非常简单

  CAS:compareAndSet,Unsafe的CAS方法的语义是先与期望值进行比较,若不相等返回false;若相等的话,则会把原值修改为新值,再返回true。这个跟 java.util.concurrent.atomic的原子类的CAS方法是一样的

  AQS的实现依赖LockSupport完成阻塞和唤醒,也正是LockSupport的引入使用AQS源码阅读起来逻辑上有点跳跃。

  什么是自旋锁,如下实例实现的即是自旋锁,即是循环等待信息量变成期望值后完成相关操作

 1 // 来自 AQS#doAcquireInterruptibly
 2 private void doAcquireInterruptibly(int arg) throws InterruptedException {
 3     final Node node = addWaiter(Node.EXCLUSIVE);
 4     boolean failed = true;
 5     try {
 6         for (;;) { // 自旋锁
 7             final Node p = node.predecessor();
 8             if (p == head && tryAcquire(arg)) { // 相当于阻塞到信号量变成期望值
 9                 setHead(node);
10                 p.next = null; // help GC
11                 failed = false;
12                 return;
13             }
14             if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
15                 throw new InterruptedException();
16         }
17     } finally {
18         if (failed)
19             cancelAcquire(node);
20     }
21 }

注:CAS算法,也有点自旋的意思,当出现多线程问题时,会不停地循环发送请求,

  Jdk1.5以后,提供了java.util.concurrent.atomic包,这个包里面提供了一组原子类

  我们来看一段AtomicBoolean中的自旋锁的代码

public final boolean getAndSet(boolean newValue) {
   for (;;) {
       boolean current = get();
       if (compareAndSet(current, newValue))
           return current;
   }
}



四、用法

4.JUC之AQS框架

标签:ansi   map   ack   sse   private   add   相关   共享模式   构造方法   

原文地址:http://www.cnblogs.com/xuzekun/p/7483978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!