BlockingQueue源码解析jdk1.8
来源:互联网 发布:lua c 数据传递 编辑:程序博客网 时间:2024/06/11 02:31
java实现BlockingQueue接口的队列源码解析
- java实现BlockingQueue接口的队列解析
- 一jdk中的阻塞队列概况
- 二阻塞队列与非阻塞队列中的方法对比
- 非阻塞队列常用方法
- 阻塞队列常用方法
- 三各阻塞队列实现原理
- ArrayBlockingQueue
- LinkerBlockingQueue
- PriorityBlockingQueue
- DelayQueue
- SynchronousQueue
- DelayedWorkQueue
- TransferQueue
阻塞队列与非阻塞队列一个最大的区别就是:阻塞队列能够阻塞当前试图从队列中获取元素的线程,而非阻塞队列不会。因此在面对类似消费者-生产者的模型时,使用非阻塞队列就必须额外地实现同步策略以及线程间唤醒策略,这个实现起来就非常麻烦。但是有了阻塞队列就不一样了,它会对当前线程产生阻塞,比如一个线程从一个空的阻塞队列中取元素,此时线程会被阻塞直到阻塞队列中有了元素。当队列中有元素后,被阻塞的线程会自动被唤醒(不需要我们编写代码去唤醒)。这样提供了极大的方便性。
一.jdk中的阻塞队列概况
阻塞队列由BlockingQueue进行定义。在jdk 1.8中实现了该接口的主要有以下几个:
ArrayBlockingQueue –基于数组实现的一个阻塞队列,在创建ArrayBlockingQueue对象时必须制定容量大小。并且可以指定公平性与非公平性,默认情况下为非公平的,即不保证等待时间最长的线程最优先能够访问队列。
LinkedBlockingQueue–基于链表实现的一个阻塞队列,在创建LinkedBlockingQueue对象时如果不指定容量大小,则默认大小为Integer.MAX_VALUE。
PriorityBlockingQueue–无界阻塞队列,它会按照元素的优先级对元素进行排序,按照优先级顺序出队,每次出队的元素都是优先级最高的元素。
DelayQueue –基于PriorityQueue实现的延迟队列,是一个无界的阻塞队列,用于放置实现了Delayed接口的对象,其中的对象只能在其到期时才能从队列中取走。因此向队列中插入时永远不会阻塞,获取时才有可能被阻塞。
SynchronousQueue –同步阻塞队列,队列大小为1,一个元素要放到该队列中必须有一个线程在等待获取元素。
DelayedWorkQueue –该队列为ScheduledThreadPoolExecutor中的静态内部类,ScheduledThreadPoolExecutor便是通过该队列使得队列中的元素按一定顺序排列从而时延迟任务和周期性任务得以顺利执行。
BlockingDeque–双向阻塞队列的接口。
TransferQueue–接口,定义了另一种阻塞情况:生产者会一直阻塞直到所添加到队列的元素被某一个消费者所消费,而BlockingQueue只需将元素添加到队列中后生产者便会停止被阻塞。
二.阻塞队列与非阻塞队列中的方法对比
非阻塞队列常用方法
在非阻塞队列中常用的操作队列的方法主要是下面几种:
add(E e):将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则会抛出异常;
remove():移除队首元素,若移除成功,则返回true;如果移除失败(队列为空),则会抛出异常;
offer(E e):将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则返回false;
poll():移除并获取队首元素,若成功,则返回队首元素;否则返回null;
peek():获取队首元素,但不移除。若成功,则返回队首元素;否则返回null
对于非阻塞队列,一般情况下建议使用offer、poll和peek三个方法,不建议使用add和remove方法。原因看上面的描述很明显了:使用offer、poll和peek三个方法可以通过返回值判断操作成功与否,而使用add和remove方法需要捕获异常才能判断操作是否成功。另外需要注意非阻塞队列的这些方法都没有进行同步处理。
阻塞队列常用方法
阻塞队列也实现了Queue,因此也具有上述方法并且都进行了同步处理。除此之外还有4个很有用的方法:
put(E e):向队尾存入元素,如果队列满,则等待;
take():从队首取元素,如果队列为空,则等待;
offer(E e,long timeout, TimeUnit unit):向队尾存入元素,如果队列满,则等待一定的时间,当时间期限达到时,如果还没有插入成功,则返回false;否则返回true;
poll(long timeout, TimeUnit unit):从队首取元素,如果队列空,则等待一定的时间,当时间期限达到时,如果取不到,则返回null;否则返回取得的元素;
三.各阻塞队列实现原理
ArrayBlockingQueue
首先看一下类中的成员变量
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
可以看到使用数组来保存元素。takeIndex是队首下标,putIndex是队尾下标,count是队列中元素数目。lock是一个可重入锁,notEmpty和notFull是等待条件。关于可重入锁和Condition的相关知识将会在其他博客中阐述。
再来看看它的构造函数
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
在来看看它的两个关键方法put和take的实现方式。
首先看看put
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
代码摘自jdk1.8,之前的代码和它稍有不同但核心没变。首先获取锁,判断当前队列是否满,满则阻塞,被其他线程唤醒时拆入元素,插入成功后通过notEmpty.signal()唤醒因队列为空等待取元素的线程。最后释放锁。
再来看看take
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
依然是先获取锁,若队列为空则等待,被其他线程唤醒后调用dequeue方法获取元素,获取成功后通过notFull.signal();唤醒因队列满无法放元素的线程
LinkerBlockingQueue
LinkerBlockingQueue使用node结构来存储数据
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
put和take方法和ArrayBlockingQueue类似,这里就不阐述了,感兴趣的读者可以自行阅读源码
PriorityBlockingQueue
该队列为无界队列并且会按照元素的优先级对元素进行排序。首先看一下成员变量
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
PriorityBlockingQueue使用数组保存元素,在空间不够时会进行扩容。每个参数的含义上面的英文注释写的很清楚了,为阅读方便这里再用中文简单解释一下:
DEFAULT_INITIAL_CAPACITY - 初始时的数组大小
MAX_ARRAY_SIZE - 数组最大值
queue - 保存元素的数组,其实被实现为了一个最大堆
size - 保存队列中元素个数
comparator - 比较元素优先级使用的Comparator
lock - 同步用的可重入锁
notEmpty - 同步用的Condition
allocationSpinLock - 该int值配合unsafe类实现了一个同步用的自旋锁,后续代码中将能看到
q - 为了兼容老代码在序列化和反序列化时使用的队列,只有在序列化/反序列化时该队列中才有值。可以看到前面用于保存元素的queue被transient修饰,因此序列化时只能通过该对象q
在看看构造函数
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
提供4种构造函数,无参的构造函数初始队列大小为11,也可指定初始队列大小及比较方法,以及用已有的集合创建队列等。下面来看看核心的put和take方法。
首先看一下put
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
put委托给了offer实现,首先是获取锁,判断队列是否还能放入元素,不能则进行扩容,看看扩容方法的实现
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
扩容时进行了同步处理。在数组小于64时每次扩容约2倍,大于64时每次扩容约1.5倍。
在回头继续看offer方法,扩容完成后如果传入comparator则调用siftUpComparable插入元素,看看其中的具体实现:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
其实就是一个最大堆的插入过程,调整堆中节点位置使最大堆元素在堆顶即array[0]的位置。siftUpUsingComparator的实现与它基本一样,就不阐述了。
元素放入数组后调用notEmpty.signal();唤醒因队列空等待的线程并释放锁。
在看看take方法
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
若队列为空则等待,将获取元素委托给了dequeue(),看看它的实现
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
返回数组头部即堆顶的元素并对堆进行调整。看看调整堆的siftDownComparable方法
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
一个典型的最大堆移除堆顶元素后的调整过程,siftDownUsingComparator与其类似,就不阐述了。
对最大堆的建立和调整还有疑问的同学可以参考这两篇博客:
http://blog.csdn.net/kobejayandy/article/details/46832797
http://februus.iteye.com/blog/1288305
DelayQueue
还是先来看一下类中的成员变量
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
可以看到,使用PriorityQueue来作为队列保存数据。其他几个变量含义都好理解,特殊的是这个leader,它是用来干嘛的呢?首先看一下jdk给出的解释:
/** * Thread designated to wait for the element at the head of * the queue. This variant of the Leader-Follower pattern * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to * minimize unnecessary timed waiting. When a thread becomes * the leader, it waits only for the next delay to elapse, but * other threads await indefinitely. The leader thread must * signal some other thread before returning from take() or * poll(...), unless some other thread becomes leader in the * interim. Whenever the head of the queue is replaced with * an element with an earlier expiration time, the leader * field is invalidated by being reset to null, and some * waiting thread, but not necessarily the current leader, is * signalled. So waiting threads must be prepared to acquire * and lose leadership while waiting. */
大致解释一下这段英文:这个leader变量用于存储等待队列中头元素的线程,使用这种领导者-追随者模式是为了减少多余的等待,领导者线程只用等待下一个元素能被获取,而其他线程则需继续等待成为领导者。领导者线程在进行take或者poll操作后需唤醒其他线程竞争领导者。当头元素发生变换时领导者或重置。
原谅我英语渣翻译得不好,总之简单一句话概括:这个Thread类型的变量即当前能获取到队列头元素的线程。稍后我们看源码能看到它是怎么被使用的。
再来看一下这个类的构造函数:
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
没有可多说的,一个无参构造函数和一个用指定集合构建队列的构造函数。
再看看核心的put和take方法。先看put
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
依然是交给了offer实现,先加锁,然后放入元素,若放入的元素成为了头元素则将leader置为null并唤醒在等待available的线程。
再来看看take的实现
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
首先依然是加锁,然后获取队列中的头元素但是不移除,如果头元素为空则阻塞线程。若不为空,判断其等待时间是否结束,结束则返回。若等待时间未结束,判断当前是否已有leader线程,有则直接阻塞,无责将leader线程设置为当前线程,并设置其在到达delay时间前阻塞(即队列头元素的等待时间前)。
看到这里应该明白为什么当有新元素成为头元素时要设leader为null并且唤醒所有等待线程了吧?当有新元素成为头元素时原leader的等待时间已经无效了,此时所有等待的线程将再一次竞争leader并等待获取头元素。精妙的设计!
SynchronousQueue
这是一个很特殊的queue,它的内部没有任何存储空间。生产者线程对其的插入操作put必须等待消费者的移除操作take,反过来也一样。因此你不能调用peek()方法来看队列中是否有数据元素,因为数据元素只有当你试着取走的时候才可能存在,不取走而只想偷窥一下是不行的,当然遍历这个队列的操作也是不允许的。数据是在配对的生产者和消费者线程之间直接传递的,并不会将数据缓冲数据到队列中。可以这样来理解:生产者和消费者互相等待对方,握手,然后一起离开。
首先看一下构造函数签名
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
两种构造函数,无参的构造函数创建非公平的SynchronousQueue,或是可以指定SynchronousQueue的公平性。可以看到是否公平是看transferer的实力化对象来决定的。非公平竞争模式使用的数据结构TransferStack是后进先出栈(Lifo Stack);公平竞争模式使用的数据结构TransferQueue是先进先出队列(Fifo Queue),但从性能上来讲非公平模式更快。
再来看看put和take方法
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
可以看到都是调用了transferer.transfer方法来完成put和take。因此下面我们来看看SynchronousQueue中的核心:Transferer接口。
- 1
- 2
- 3
- 1
- 2
- 3
方法transfer中3个参数的含义分别为:
e – 为空则是需要消费元素,不为空则是要放入的元素
timed – 是否允许超市
nanos – 超时时间,纳秒级别
在SynchronousQueue给出了该接口的两个实现:TransferQueue和TransferStack。TransferQueue用于构建公平的SynchronousQueue,TransferStack用于构建非公平的SynchronousQueue。首先我们来看看TransferQueue中transfer方法的实现:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
QNode是TransferQueue中的静态内部类,保存节点信息
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
总体分析,该方法中的同步策略都没有使用锁,同步通过spin(我理解为忙等)和cas(Compare and Swap)的方法来实现。
这段代码的实现逻辑我直接翻译jdk中的原文吧,原文如下:
/* Basic algorithm is to loop trying to take either of
* two actions:
*
* 1. If queue apparently empty or holding same-mode nodes,
* try to add node to queue of waiters, wait to be
* fulfilled (or cancelled) and return matching item.
*
* 2. If queue apparently contains waiting items, and this
* call is of complementary mode, try to fulfill by CAS’ing
* item field of waiting node and dequeuing it, and then
* returning matching item.
*
* In each case, along the way, check for and try to help
* advance head and tail on behalf of other stalled/slow
* threads.
*
* The loop starts off with a null check guarding against
* seeing uninitialized head or tail values. This never
* happens in current SynchronousQueue, but could if
* callers held non-volatile/final ref to the
* transferer. The check is here anyway because it places
* null checks at top of loop, which is usually faster
* than having them implicitly interspersed.
*/
大致谈一下自己的理解:队列中保存的都是执行相同操作的线程(都是take或都是put,即都是生产者或都是消费者),当另一种类型的线程进入后,与队列中的头元素进行匹配,完成数据的传输。
再来看看TransferStack中transfer的实现
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
看看jdk对这段代码的解释
/*
* Basic algorithm is to loop trying one of three actions:
*
* 1. If apparently empty or already containing nodes of same
* mode, try to push node on stack and wait for a match,
* returning it, or null if cancelled.
*
* 2. If apparently containing node of complementary mode,
* try to push a fulfilling node on to stack, match
* with corresponding waiting node, pop both from
* stack, and return matched item. The matching or
* unlinking might not actually be necessary because of
* other threads performing action 3:
*
* 3. If top of stack already holds another fulfilling node,
* help it out by doing its match and/or pop
* operations, and then continue. The code for helping
* is essentially the same as for fulfilling, except
* that it doesn’t return the item.
*/
循环等待3种行为中的一种发生:
1.如果栈为空或存在相同模式的节点(同为消费者或生产者)则将新节点加入栈中等待被匹配;
2.如果新节点与栈顶节点匹配,则将新节点入栈并与其匹配,匹配完成后弹出两个节点并返回值
3.如果新节点加入时发现另一个节点正在匹配,则帮助它匹配完成后再继续。
关于synchronousqueue还有不清楚的同学,强烈推荐这篇论文:http://www.cs.rochester.edu/u/scott/papers/2009_Scherer_CACM_SSQ.pdf
也可以参考这篇博文:http://blog.csdn.net/jy3161286/article/details/22993963?utm_source=tuicool&utm_medium=referral
DelayedWorkQueue
该队列作为静态内部类实现在ScheduledThreadPoolExecutor中。首先来看看它其中的变量
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
使用数组来存储队列中的数据,实际上数组被用来实现堆。初始化数组大小16。
再来看看put
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
有没有觉得很眼熟?和PriorityBlockingQueue的put大同小异。实际上扩容和放入元素并调整堆的方法也是类似的
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
就不阐述了,有疑问的同学可以翻到上面看看对PriorityBlockingQueue实现的解释。
在看看take
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
和PriorityBlockingQueue一样,不详述了
TransferQueue
这是一个接口,新添加的transfer方法用来实现这种约束:生产者会一直阻塞直到所添加到队列的元素被某一个消费者所消费。顾名思义,阻塞就是发生在元素从一个线程transfer到另一个线程的过程中,它有效地实现了元素在线程之间的传递。除了transfer还包括一些其他方法,看看该接口的方法列表:
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
关于TransferQueue存在的意义和性能可以操考下面的资料
当我第一次看到TransferQueue时,首先想到了已有的实现类SynchronousQueue。SynchronousQueue的队列长度为0,最初我认为这好像没多大用处,但后来我发现它是整个Java
Collection Framework中最有用的队列实现类之一,特别是对于两个线程之间传递元素这种用例。TransferQueue相比SynchronousQueue用处更广、更好用,因为你可以决定是使用BlockingQueue的方法(译者注:例如put方法)还是确保一次传递完成(译者注:即transfer方法)。在队列中已有元素的情况下,调用transfer方法,可以确保队列中被传递元素之前的所有元素都能被处理。Doug
Lea说从功能角度来讲,LinkedTransferQueue实际上是ConcurrentLinkedQueue、SynchronousQueue(公平模式)和LinkedBlockingQueue的超集。而且LinkedTransferQueue更好用,因为它不仅仅综合了这几个类的功能,同时也提供了更高效的实现。Joe Bowbeer提供了一篇William Scherer, Doug Lea, and Michael
Scott的论文,在这篇论文中展示了LinkedTransferQueue的算法,性能测试的结果表明它优于Java
5的那些类(译者注:ConcurrentLinkedQueue、SynchronousQueue和LinkedBlockingQueue)。LinkedTransferQueue的性能分别是SynchronousQueue的3倍(非公平模式)和14倍(公平模式)。因为像ThreadPoolExecutor这样的类在任务传递时都是使用SynchronousQueue,所以使用LinkedTransferQueue来代替SynchronousQueue也会使得ThreadPoolExecutor得到相应的性能提升。考虑到executor在并发编程中的重要性,你就会理解添加这个实现类的重要性了。
引自http://ifeve.com/java-transfer-queue/
jdk1.8中唯一实现了该接口的实现时LinkedTransferQueue,下面我们从该类进行研究。
首先看一下LinkedTransferQueue中实现队列的数据结构node
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
LinkedTransferQueue中无论是transfer、tryTransfer、put、take方法都是调用的xfer方法,因此直接来看该方法的实现了
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
代码注释的翻译参考自:http://www.cnblogs.com/rockman12352/p/3790245.html?utm_source=tuicool&utm_medium=referral
但博文中给出的示例有误,示例可参考下面:
给4个示例更方便理解:
情况一:
1:Head->Data Input->Data 队列中已有元素,再放入元素
Match: 根据他们的属性发现 cannot match ,因为是同类的
处理节点: 把新的data放在原来的data后面
HEAD->DATA->DATA
情况二:
2:Head->waiter Input->waiter 队列中已有消费者等待,再获取元素
Match: 根据他们的属性发现 cannot match ,因为是同类的
处理节点: 把新的waiter放在原来的waiter后面,然后head往后移一位。
HEAD->waiter->waiter
情况三:
3:Head->waiter Input->Data 队列中已有消费者等待,添加数据
Match: 成功match,就把waiter对应node的item变为Data的值(有主了),并且叫waiter来取
处理节点:head后移一位
HEAD=waiter(用过)
情况四:
4:Head->Data Input->waiter 队列中已有数据,新加入消费者
Match: 成功match,就把Data的item变为waiter的值(即null,有主了),并且返回数据。
处理节点:head后移一位
HEAD=DATA(用过)
看到一篇博文中说该类有bug,有兴趣的同学可以看看:
http://ifeve.com/buglinkedtransferqueue-bug/
经测试在目前最新的jdk “1.8.0_91”中博主所说的’bug’仍然存在。简单来说在这种情况下会发生’bug’:
队列为空或队列前面的元素已全部完成匹配,此时一个消费者线程进入,假设为t1,因队列空或已全部匹配,其无法匹配,准备开始运行tryAppend方法,
- 1
- 1
此时又进入一个与t1模式相同的线程抢占了cpu(即也是消费者线程),设为t2。此时t1还未完成tryAppend方法的运行,所以队列仍然为空,t2准备开始运行tryAppend方法。此时又进入一个生产者线程t3抢占了cpu,因为t1,t2都没有完成tryAppend方法的运行,所以队列仍然为空,t3准备运行tryAppend方法。(以上步骤顺序可随意颠倒,即可以是t3先运行到tryAppend处阻塞,然后t2,t1抢占,等等。关键在3个线程都阻塞在了tryAppend开始处。)此时t1重新获得cpu,运行完成tryAppend方法将自己加入队列,t2重新获得cpu,运行完成tryAppend方法将自己加入队列。此时t2的中断被出发,t2中断,按LinkedTransferQueue的逻辑t1和t2变为匹配状态。t3重新获得cpu,执行tryAppend。按常理此时执行tryAppend应该失败,然后重新进入xfer()的循环中,因为队列中已有两个与t3相反模式的节点。但是因为LinkedTransferQueue判断t1和t2已匹配,队列即将为空,所以t3也成功加入了队列。
此时队列状况为:
t1->t2->t3
假设接下来又进入一个消费者线程t4,在执行到xfer()的这里时将直接break
- 1
- 2
- 1
- 2
代码中isData取值来自
- 1
- 1
p指向头节点。haveData即标明t4是消费者还是生产者。显然这里isData和haveData都是fales
接下来执行这段代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
因为无法匹配t4也执行tryAppend尝试加入队列,在加入队列时会判断尾节点模式是否和t4一样,上面说了此时尾节点是t3,模式是生产者与t4相反,所以t4加入队列失败,返回null,即执行代码
- 1
- 2
- 1
- 2
又进入了一开始的循环:和头节点模式相同,判断无法完成匹配,尝试加入队列,加入队列时发现尾节点模式和自己相反,无法加入,重试,判断头节点模式相同,无法完成匹配…
t4就这样无限循环了 T T
此时如果有更多消费者线程进来,都将在这里无限循环,cpu飙升
但是!!
如果这时有一个新的生成者线程t5进入,从xfer()方法的头部开始执行,判断头元素与自己模式相反,可以完成匹配,运行到这里
- 1
- 1
刚才阻塞的t1线程将被唤醒,并且能够接受数据数据。头节点将重新指向t3(因为t2已中断,是无效节点),t4的无限循环也被打破,和t5完成匹配,队列恢复正常。
so,在实际使用中不光这个bug出现概率极低,就算出现后只要一个新的生成者到来就能自己恢复正常。不过你可能还是会担心,万一这段时间到来的全是消费者cpu不是gg?为了避免这种情况,jdk1.8中在该类新增了扫描的机制,
* In addition to minimizing garbage retention via self-linking * described above, we also unlink removed interior nodes. These * may arise due to timed out or interrupted waits, or calls to * remove(x) or Iterator.remove. Normally, given a node that was * at one time known to be the predecessor of some node s that is * to be removed, we can unsplice s by CASing the next field of * its predecessor if it still points to s (otherwise s must * already have been removed or is now offlist). But there are two * situations in which we cannot guarantee to make node s * unreachable in this way: (1) If s is the trailing node of list * (i.e., with null next), then it is pinned as the target node * for appends, so can only be removed later after other nodes are * appended. (2) We cannot necessarily unlink s given a * predecessor node that is matched (including the case of being * cancelled): the predecessor may already be unspliced, in which * case some previous reachable node may still point to s. * (For further explanation see Herlihy & Shavit "The Art of * Multiprocessor Programming" chapter 9). Although, in both * cases, we can rule out the need for further action if either s * or its predecessor are (or can be made to be) at, or fall off * from, the head of list. * * Without taking these into account, it would be possible for an * unbounded number of supposedly removed nodes to remain * reachable. Situations leading to such buildup are uncommon but * can occur in practice; for example when a series of short timed * calls to poll repeatedly time out but never otherwise fall off * the list because of an untimed call to take at the front of the * queue. * * When these cases arise, rather than always retraversing the * entire list to find an actual predecessor to unlink (which * won't help for case (1) anyway), we record a conservative * estimate of possible unsplice failures (in "sweepVotes"). * We trigger a full sweep when the estimate exceeds a threshold * ("SWEEP_THRESHOLD") indicating the maximum number of estimated * removal failures to tolerate before sweeping through, unlinking * cancelled nodes that were not unlinked upon initial removal. * We perform sweeps by the thread hitting threshold (rather than * background threads or by spreading work to other threads) * because in the main contexts in which removal occurs, the * caller is already timed-out, cancelled, or performing a * potentially O(n) operation (e.g. remove(x)), none of which are * time-critical enough to warrant the overhead that alternatives * would impose on other threads. * * Because the sweepVotes estimate is conservative, and because * nodes become unlinked "naturally" as they fall off the head of * the queue, and because we allow votes to accumulate even while * sweeps are in progress, there are typically significantly fewer * such nodes than estimated. Choice of a threshold value * balances the likelihood of wasted effort and contention, versus * providing a worst-case bound on retention of interior nodes in * quiescent queues. The value defined below was chosen * empirically to balance these under various timeout scenarios. * * Note that we cannot self-link unlinked interior nodes during * sweeps. However, the associated garbage chains terminate when * some successor ultimately falls off the head of the list and is * self-linked. */
我们刚才遭遇的就是上面的case2了。这里也解释了为什么不使用http://ifeve.com/buglinkedtransferqueue-bug/ 这篇博文中的方法解决该问题。
所以在jdk1.8中,愉快的使用LinkedTransferQueue吧^ ^
- BlockingQueue源码解析jdk1.8
- Java源码解析-BlockingQueue
- HashMap 源码解析(JDK1.8)
- JDK1.8 StampedLock源码解析
- ArrayList源码解析(jdk1.8)
- Vector源码解析(jdk1.8)
- LinkedList源码解析(jdk1.8)
- jdk1.8----ArrayList源码解析
- jdk1.8 String源码解析
- [数据结构]--jdk1.8中HashMap源码解析
- JDK1.8源码解析之 HashMap
- JDK1.8 HashMap putValue源码解析
- ArrayList源码解析——JDK1.8
- LinkedList源码解析——JDK1.8
- CopyOnWriteArrayList源码解析——JDK1.8
- jdk1.8中arrayList源码解析
- java jdk1.8 LinkedList源码解析
- JDK1.8 动态代理机制及源码解析
- 算法设计与应用基础系列16
- LeetCode 535 Encode and Decode TinyURL (HashMap)
- c++11 新特性
- cups数据自动导入软件开发
- 二分查找变形记:从循环不变量说起
- BlockingQueue源码解析jdk1.8
- SylixOS启动读取配置文件
- 数据库 之 超键、候选键、主键、主属性、外键
- 指针数组及数组指针
- asp.net中iframe详细用法
- docker私有仓库搭建
- Android常用开源项目(十四)
- Android JSON数据解析详细用法
- STL简介