java轻松实现无锁队列
1、什么是无锁(Lock-Free)编程
当谈及 Lock-Free 编程时,我们常将其概念与 Mutex(互斥) 或 Lock(锁) 联系在一起,描述要在编程中尽量少使用这些锁结构,降低线程间互相阻塞的机会,以提高应用程序的性能。类同的概念还有 "Lockless" 和 "Non-Blocking" 等。实际上,这样的描述只涵盖了 Lock-Free编程的一部分内容。本质上说,Lock-Free 编程仅描述了代码所表述的性质,而没有限定或要求代码该如何编写。
基本上,如果程序中的某一部分符合下面的条件判定描述,则我们称这部分程序是符合 Lock-Free的。反过来说,如果某一部分程序不符合下面的条件描述,则称这部分程序是不符合 Lock-Free 的。
上面的英文翻译成中文就是很简单的:如果你的应用程序是多线程并且它们之间都有访问共享内存但是访问时并没有相互阻塞,那它就是lock-free编程。注意lock-free只是强调了编程概念并没指定其具体的实现形式,其强调的概念是「线程间访问共享内存时不会相互阻塞」。那如果没有lock或者Mutex就一定是lock-free编程了吗,看下面的代码片段:
x = 0; while(x == 0){ x = 1 - x; }
假设有线程T1,T2同时调用这段代码,T1,T2都判断x == 0,进行到循环。T1先执行 x = 1 - 0,此时 x = 1后 T2 执行 x = 1 - 1。x = 0。T1,T2此时判断x == 0,结果两者又进入了循环。。。线程T1,T2相互影响,两者都陷入了死循环,这种某种意义也算得上是相互阻塞使线程,所以这不算是lock-free编程。
ok,了解了lock-free编程的相关概念那要怎么实现呢。在开始说无锁队列之前,我们需要知道一个很重要的技术就是CAS操作——Compare & Set,或是 Compare & Swap,现在几乎所有的CPU指令都支持CAS的原子操作,X86下对应的是 CMPXCHG 汇编指令。有了这个原子操作,我们就可以用其来实现各种无锁(lock free)的数据结构。
这个操作用C语言来描述就是下面这个样子:意思就是说,看一看内存*reg里的值是不是oldval,如果是的话,则对其赋值newval。
1
2
3
4
5
6
7
|
int compare_and_swap ( int * reg, int oldval, int newval) { int old_reg_val = *reg; if (old_reg_val == oldval) *reg = newval; return old_reg_val; } |
用JAVA语言则是:
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
了解了CAS操作之后实现lock-free数据结构思路是怎样呢?这里就有篇论文讲述了思路:http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.53.8674&rep=rep1&type=pdf。其中里面就提到了如何用数组实现一个lock-free队列。有兴趣的朋友可以参考上面链接阅读里面的第5章节。现在说一下我自己具体的实现思路:
- 数组队列是一个循环数组,队列少用一个元素,当头等于尾标示队空,尾加1等于头标示队满。
- 数组的元素用EMPTY(无数据,标示可以入队)和FULL(有数据,标示可以出队)标记指示,数组一开始全部初始化成 EMPTY标示空队列。
- EnQue 操作:如果当前队尾位置为EMPTY,标示线程可以在当前位置入队,通过CAS原子操作把该位置设置为FULL,避免其它线程操作这个位置,操作完后修改队尾位置。各个线程竞争新的队尾位置。如下图所示:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA44AAACrCAIAAACmHFXbAAAZVUlEQVR4nO3cT2sbVxfA4X6Y+EsYLaaLulBCjLzq0iCvunJg6CobFyZ05WShVRaxYcgq3cwqxFC0MAgMA4GaLgYX4qStGpp4kUwSS0lavYvz+no6cvxHmrl37tHvWRRZkpt7xufcczQa6Ysx5kme566XAGAmVDEA546Ojqz9W19Y+5fQBN99953N9AJQrdFotLa2NhqNXC8EwPwajUbffvuttXGCUXWO7O7uBkHQ7XZdLwTAlB48eBAEQZIkrhcCYH7JRmRtnGBUnSO3bt0KgiAIgoODA9drAXBlR0dHS0tLQRCsra25XguAOWU2ImvjBKPqvDg4OAhO3Lp1y/VyAFxZt9s1Vby7u+t6OQDmUXEjsjNOMKrOi83NzaBgb2/P9YoAXEHx1SYvOAE4UdqI7IwTjKpzoXi6XvAGIuAXcwGPwZU8ACyb3IgsjBOMqnNha2srmPDo0SPX6wJwKXt7e5MlvLm56XpdAObImRuRhXGCUVW/0Wi0srIymVsrKyt85Q3ghbW1tckSXlpa4rvnAFhz5kZkYZxgVNXv0aNHP/74497eXp7nQRCMx+PRaPTkyZPNzc2ff/7Z9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LgBzZG9v78GDB0dHR/Kj2Yj++uuve/fu1TpOMKrqd3R0tLS0tLKysr6+HgTB+vr6+vr6ysrK0tKSyTkAjTUajVZWVq5fvy7FK1X87bffBkFwcHDgenUA5oJsRGaKkBtra2tBENQ9TjCqzoXNzc1gwr1791yvC8ClPHz4cLKEb9265XpdAObImRuRhXGCUXUuHBwclBJrZWXFvJ8IoPnk7EUR7/4DsGxyI7IwTjCqzotbt24Vc+vhw4euVwTgCnZ3d4slvLa25npFAOZOaSOyM04wqs6LYnrR5AAfff/996aKkyRxvRwA86i4EdkZJxhV54g5b8/7hoCPzJU8XMADwJXiJYV2xglG1TmSJEkQBN9//73rhQCY0o8//hgEwdbWluuFAJhfshFZGycYVeeIfNME324D+Ovo6Oj69et8zRwAh+RLMK2NE4yq84U5FfAdVQzAuSdPnlj7t/4H/WYhCQeqCFQAAAAASUVORK5CYII=" alt="" />
下面是贴上具体的代码:
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray; /**
* 用数组实现无锁有界队列
*/ public class LockFreeQueue { private AtomicReferenceArray atomicReferenceArray;
//代表为空,没有元素
private static final Integer EMPTY = null;
//头指针,尾指针
AtomicInteger head,tail; public LockFreeQueue(int size){
atomicReferenceArray = new AtomicReferenceArray(new Integer[size + 1]);
head = new AtomicInteger(0);
tail = new AtomicInteger(0);
} /**
* 入队
* @param element
* @return
*/
public boolean add(Integer element){
int index = (tail.get() + 1) % atomicReferenceArray.length();
if( index == head.get() % atomicReferenceArray.length()){
System.out.println("当前队列已满,"+ element+"无法入队!");
return false;
}
while(!atomicReferenceArray.compareAndSet(index,EMPTY,element)){
return add(element);
}
tail.incrementAndGet(); //移动尾指针
System.out.println("入队成功!" + element);
return true;
} /**
* 出队
* @return
*/
public Integer poll(){
if(head.get() == tail.get()){
System.out.println("当前队列为空");
return null;
}
int index = (head.get() + 1) % atomicReferenceArray.length();
Integer ele = (Integer) atomicReferenceArray.get(index);
if(ele == null){ //有可能其它线程也在出队
return poll();
}
while(!atomicReferenceArray.compareAndSet(index,ele,EMPTY)){
return poll();
}
head.incrementAndGet();
System.out.println("出队成功!" + ele);
return ele;
} public void print(){
StringBuffer buffer = new StringBuffer("[");
for(int i = 0; i < atomicReferenceArray.length() ; i++){
if(i == head.get() || atomicReferenceArray.get(i) == null){
continue;
}
buffer.append(atomicReferenceArray.get(i) + ",");
}
buffer.deleteCharAt(buffer.length() - 1);
buffer.append("]");
System.out.println("队列内容:" +buffer.toString()); } }
代码很简单,相应的注释也写上了,相信大家都应该看得懂~。
这里说明一下JDK提供的CAS原子操作类都位于 java.util.concurrent.atomic下面。这里用到的是数组我用的是AtomicReferenceArray类,当然你也可以用AtomicIntegerArray。这里用到了两个原子类的作为指针head,tail,利用mod队列的长度来实现一个循环数组。
下面测试我们的代码:
import java.util.stream.IntStream; public class LockFreeDemo {
public static void main(String[] args) {
LockFreeQueue queue = new LockFreeQueue(5);
IntStream.rangeClosed(1, 10).parallel().forEach(
i -> {
if (i % 2 == 0) {
queue.add(i);
} else {
queue.poll();
}
}
);
queue.print();
}
}
这里面用了JDK8的lambda并行流的特性,起了Ncpu线程去并发得入队和出队。运行结果如下:
入队成功!2
当前队列为空
当前队列为空
入队成功!6
当前队列为空
入队成功!8
出队成功!2
入队成功!10
出队成功!6
入队成功!4
队列内容:[4,8,10]
因为是并发打印,所以打出来的信息整体是无序的,但是对于同一个元素的操作,我们看到是相对有序的~
java轻松实现无锁队列的更多相关文章
- HashMap的原理与实 无锁队列的实现Java HashMap的死循环 red black tree
http://www.cnblogs.com/fornever/archive/2011/12/02/2270692.html https://zh.wikipedia.org/wiki/%E7%BA ...
- Go语言无锁队列组件的实现 (chan/interface/select)
1. 背景 go代码中要实现异步很简单,go funcName(). 但是进程需要控制协程数量在合理范围内,对应大批量任务可以使用"协程池 + 无锁队列"实现. 2. golang ...
- 无锁队列以及ABA问题
队列是我们非常常用的数据结构,用来提供数据的写入和读取功能,而且通常在不同线程之间作为数据通信的桥梁.不过在将无锁队列的算法之前,需要先了解一下CAS(compare and swap)的原理.由于多 ...
- zeromq源码分析笔记之无锁队列ypipe_t(3)
在上一篇中说到了mailbox_t的底层实际上使用了管道ypipe_t来存储命令.而ypipe_t实质上是一个无锁队列,其底层使用了yqueue_t队列,ypipe_t是对yueue_t的再包装,所以 ...
- boost 无锁队列
一哥们翻译的boost的无锁队列的官方文档 原文地址:http://blog.csdn.net/great3779/article/details/8765103 Boost_1_53_0终于迎来了久 ...
- 一个可无限伸缩且无ABA问题的无锁队列
关于无锁队列,详细的介绍请参考陈硕先生的<无锁队列的实现>一文.然进一步,如何实现一个不限node数目即能够无限伸缩的无锁队列,即是本文的要旨. 无锁队列有两种实现形式,分别是数组与链表. ...
- 无锁队列--基于linuxkfifo实现
一直想写一个无锁队列,为了提高项目的背景效率. 有机会看到linux核心kfifo.h 原则. 所以这个实现自己仿照,眼下linux我们应该能够提供外部接口. #ifndef _NO_LOCK_QUE ...
- CAS简介和无锁队列的实现
Q:CAS的实现 A:gcc提供了两个函数 bool __sync_bool_compare_and_swap (type *ptr, type oldval, type newval, ...)// ...
- 基于无锁队列和c++11的高性能线程池
基于无锁队列和c++11的高性能线程池线程使用c++11库和线程池之间的消息通讯使用一个简单的无锁消息队列适用于linux平台,gcc 4.6以上 标签: <无> 代码片段(6)[ ...
随机推荐
- jenkins构建docker镜像上传到harbor并发布到kubernetes
很早之前写过一篇jenkins集成docker的文章,使用的是CloudBees Docker Build and Publish plugin插件.这篇文章是直接使用shell脚本做的,主要是这次有 ...
- js验证4位数字
var reg = /^\d{4}$/; var str = "0001"; reg.test(str);
- Hadoop生态圈-Kafka的旧API实现生产者-消费者
Hadoop生态圈-Kafka的旧API实现生产者-消费者 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.旧API实现生产者-消费者 1>.开启kafka集群 [yinz ...
- Jenkins mac pkg安装 后默认配置文件/启动路径
自启动文件路径 /Library/LaunchDaemons/org.jenkins-ci.plist jenkins.war 执行文件路径 /Applications/Jenkins/jenkins ...
- python导出数据到excel
1,SMTP发送带excel附件的邮件: def sendMail(filename, addressee): """ :param content: 发送内容 :par ...
- ajax函数说明
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...
- mysql 1045 access denied for user 解决方法
提示:1045 access denied for user 'root'@'localhost' using password yes方法一: # /etc/init.d/mysql stop # ...
- 搭建RabbitMQ集群(Docker)
前一篇搭建RabbitMQ集群(通用)只是把笔记直接移动过来了,因为我的机器硬盘已经满了,实在是开不了那么虚拟机. 还好,我的Linux中安装了Docker,这篇文章就简单介绍一下Docker中搭建R ...
- php扩展Redis功能
php扩展Redis功能 1 首先,查看所用php编译版本V6/V9 在phpinfo()中查看 2 下载扩展 地址:https://github.com/nicolasff/phpredis/dow ...
- 大数据系列之分布式计算批处理引擎MapReduce实践-排序
清明刚过,该来学习点新的知识点了. 上次说到关于MapReduce对于文本中词频的统计使用WordCount.如果还有同学不熟悉的可以参考博文大数据系列之分布式计算批处理引擎MapReduce实践. ...