当前位置:网站首页>Linked blocking Queue Analysis of blocking queue
Linked blocking Queue Analysis of blocking queue
2020-11-06 01:18:22 【Clamhub's blog】
1、 Five kinds of blocking queues are introduced
- ArrayBlockingQueue
Bounded queues , The bottom layer is implemented by array , Concurrent control use ReentrantLock control , Whether it's an insert operation or a read operation , You need to get the lock before you can execute . - LinkedBlockingQueue
The bottom layer is based on one-way linked list , It can be regarded as a bounded queue , It can also be used as an unbounded queue . Use two ReentrantLock Implement concurrency control :takelock and putlock. - SynchronousQueue
The bottom layer uses one-way linked list , There's only one element , Synchronization means that a write operation must wait for a read operation to return , It refers to the synchronization of read-write threads . - PriorityBlockingQueue
Implementation of blocking queue with sorting , Using arrays to implement . Concurrent control use ReentrantLock, The queue is unbounded .
There are initialization parameters to specify the size of the queue , But it will automatically expand . Using the smallest heap for sorting . - DelayedQueue
DelayedQueue It's using PriorityBlockingQueue and Delayed Realized , A priority queue is defined internally , When calling offer When , hold Delayed Objects are added to the queue , Use take The first first Take the object out (peek), If you don't reach the threshold , Conduct await Handle .
2、poll and peek The difference between
Are used to get the header of the queue ,poll The header node will be deleted ,peek The header node will not be deleted .
3、LinkedBlockingQueue
- It's the first in, first out line FIFO.
- use ReentrantLock Ensure thread safety
3.1、 function
3.1.1、 increase
There are three ways to increase , Premise : The queue is full
The way | put | add | offer |
---|---|---|---|
characteristic | Keep blocking | Throw exceptions | return false |
3.1.2、 Delete
There are three ways to delete , Premise : The queue is empty
The way | remove | poll | take |
---|---|---|---|
characteristic | NoSuchElementException | return false | Blocking |
3.2、 Simple analysis
- LinkedBlockingQueue It's a blocking queue , The interior is made up of two ReentrantLock To achieve thread safety in and out of the queue , By their own Condition Object's await and signal To achieve the wait and wake function .
- Based on one-way linked list 、 The range is arbitrary ( In fact, there is a boundary )、FIFO Blocking queues .
- The head and tail nodes always point to a sentinel's node in the beginning , It doesn't hold the actual data , When there is data in the queue , The head node still points to the sentinel , The tail node points to the last node of valid data . The advantage of doing so is , And counter count After combining , The team leader 、 The visit at the end of the team can be done independently , It is not necessary to judge the relationship between the head node and the tail node .
3.2.1、 Nodes and properties
1 |
// Internal class of linked list node |
3.2.2、 Insert thread and get mutual notification of thread
signalNotEmpty() Method , Called when the insertion thread finds that the queue is empty , Tell the fetch thread to wait .
signalNotFull() Method , Called when the fetch thread finds that the queue is full , Tell the insert thread to wait .
1 |
// Said wait take.put/offer call , Otherwise, it's not usually locked takeLock. |
3.2.3、 Entry and exit operations
enqueue() Methods can only be held in putLock Lock down execution ,dequeue() In the hold takeLock Lock down execution .
1 |
// Insert... At the end of the queue |
3.2.4、 Lock and release two locks
When two locks need to be locked at the same time , Encapsulate the sequence of lock and release into methods , Make sure that everything is consistent . Moreover, the lock is not responding to the interrupt , Until the lock is successful , This prevents the first lock from being locked successfully , And the second lock failed to lock, resulting in the risk that the lock will not be released .
1 |
// lock putLock and takeLock |
3.3、 Source code interpretation
A brief introduction LinkedBlockingQueue in API Source code , Such as the construction method , newly added , obtain , Delete ,drainTo.
3.3.1、 Constructors
LinkedBlockingQueue There are three construction methods , Among them, the nonparametric structure should be used as little as possible , Because the capacity is Integer The maximum of , Improper operation will cause memory overflow .
1 |
public LinkedBlockingQueue() { |
3.3.2、offer(E e)
Set the given element to the queue , If the setting is successful, return to true, Otherwise return to false. e The value of cannot be empty , Otherwise, a null pointer exception is thrown .
1 |
// If you can insert the specified element to the end of the queue immediately without exceeding the queue capacity , Return to... After success true, If the queue is full , return false. When using a queue with limited capacity , This method is usually better than method BlockingQueue#add preferable , The latter can only insert elements by throwing exceptions . |
3.3.3、put(E e)
Set the element to the queue , If there is no extra space in the queue , This method will always block , Until there's extra space in the queue .
1 |
public void put(E e) throws InterruptedException { |
3.3.4、peek()
Non blocking gets the first element in the queue , Not out of line .
1 |
public E peek() { |
3.3.5、poll()
Non blocking access to values in the queue , Return not obtained null.
1 |
public E poll() { |
3.3.6、remove(Object o)
Removes the specified value from the queue . Lock both locks .
1 |
public boolean remove(Object o) { |
3.3.7、clear()
Clear queue .
1 |
// Atomically removes all elements from the queue . When this call returns , The queue will be empty . |
3.3.8、drainTo(Collection c)
Put the median in the queue , Remove all , Set concurrency to a given set .
1 |
public int drainTo(Collection<? super E> c, int maxElements) { |
版权声明
本文为[Clamhub's blog]所创,转载请带上原文链接,感谢
边栏推荐
- OPTIMIZER_TRACE详解
- 使用Consul实现服务发现:instance-id自定义
- OPTIMIZER_ Trace details
- Using consult to realize service discovery: instance ID customization
- Summary of common string algorithms
- Summary of common algorithms of linked list
- 构建者模式(Builder pattern)
- Builder pattern
- Newbe.ObjectVisitor 样例 1
- Newbe.ObjectVisitor Example 1
猜你喜欢
-
Farewell to runaway
-
LeetCode Algorithm 0060 - Permutation Sequence (Medium)
-
编程基础 - 栈的应用 - 混洗(Stack Shuffling)
-
LeetCode Algorithm 0060 - Permutation Sequence (Medium)
-
Fundamentals of programming stack shuffling
-
【色卡】常用色谱简析,中国传统颜色卡,代码附RBG,HC
-
[color card] brief analysis of commonly used chromatograms, Chinese traditional color cards, code with RBG, HC
-
MongoDB 副本集之入门篇
-
Introduction to mongodb replica set
-
My name is mongodb, don't understand me. After reading my story, you will get started!
随机推荐
- roboguide破解安装教程
- Roboguide cracking installation tutorial
- The transformation of town street intelligent street lamp under the industrial intelligent gateway
- Remote smoke monitoring of environmental protection data acquisition instrument under Internet of things
- JS实现鼠标移入DIV随机变换颜色
- Flutter 页面中的异常处理ErrorWidget
- Exception handling errorwidget in fluent page
- Bolt's practice of route management of flutter (page decoupling, process control, function expansion, etc.)
- C语言系统化精讲 重塑你的编程思想 打造坚实的开发基础
- Skywalking系列博客6-手把手教你编写Skywalking插件
- Skywalking series blog 7 - dynamic configuration
- Skywalking series blog 6 - help you write skywalking plug-in
- 博客主机_自动申请续期免费证书
- Blog host_ Automatic renewal of free certificate
- 0x05 - 综合示例,导出 CSV
- 0x05 - synthesis example, export to CSV
- 0x02 - create and cache object visitors
- flutter圆形或线型进度条
- flutter给滚动内容添加粘性header组件
- Fluent round or linear progress bar
- Fluent adds sticky header components to scrolling content
- Typora uses latex to insert mathematical formulas
- 配电自动化终端dtu
- How to write a thesis opening report
- 基于C的PHP快速IP解析扩展,IP检测
- Based on C PHP fast IP resolution extension, IP detection
- 点击平滑滚动效果
- Click smooth scrolling effect
- HighGo Database触发器使用案例(APP)
- Use case of highgo database trigger (APP)
- ES6之Map对象
- Flutter 最常出现的错误
- Flutter's most common mistakes
- 捕获 flutter app的崩溃日志并上报
- Capture and report the crash log of the flutter app
- SQL Server递归查询在Highgo DB中实现 (APP)
- Implementation of SQL Server recursive query in highgo dB (APP)
- 关于browserslist配置项
- About browserlist configuration items
- FTK1000使用视频一招搞定多模光损耗