最近一年多写的最虐心的代码。必须好好复习java并发了。搞了一晚上终于测试都跑通过了,特此纪念,以资鼓励!

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* 实现可调整大小的阻塞队列,支持数据迁移平衡reader,writer读取吸入速度,达到最大吞吐
* @author hanjie
*
*/
public class RecordBuffer { public static final Record CLOSE_RECORD = new Record() { @Override
public Object getColumnValue(String columnName) {
// TODO Auto-generated method stub
return null;
}
}; public static final Record SWITCH_QUEUE_RECORD = new Record() { @Override
public Object getColumnValue(String columnName) {
// TODO Auto-generated method stub
return null;
}
}; public Lock switchingQueueLock = new ReentrantLock();
public Condition readerSwitched = switchingQueueLock.newCondition();
public Condition writerSwitched = switchingQueueLock.newCondition();
public Condition switchFinished = switchingQueueLock.newCondition(); public volatile boolean readerSwitchSuccess = true;
public volatile boolean writerSwitchSuccess = true;
public volatile boolean switchingQueue = false;
public volatile boolean closed = false;
private volatile ArrayBlockingQueue<Record> queue;
private TaskCounter taskCounter; public RecordBuffer(TaskCounter taskCounter, int size) {
this.queue = new ArrayBlockingQueue<Record>(size);
this.taskCounter = taskCounter;
} public void resize(int newSize) {
try { if(closed){
return;
} switchingQueueLock.lock();
try {
//double check下,要不可能writer收到CLOSED_record已经 退出了。writerSwitched.await() 会hang住
if(closed){
return;
}
this.switchingQueue = true; ArrayBlockingQueue<Record> oldQueue = queue;
queue = new ArrayBlockingQueue<Record>(newSize);
this.readerSwitchSuccess = false;
this.writerSwitchSuccess = false; //先拯救下writer,可能writer刚好阻塞到take上,失败也没关系,说明老队列不空,writer不会阻塞到take
oldQueue.offer(SWITCH_QUEUE_RECORD); while (!writerSwitchSuccess) {
writerSwitched.await();
}
//writer先切换队列,然后reader可能阻塞在最后一个put上,清空下老队列拯救reader,让它顺利醒来
transferOldQueueRecordsToNewQueue(oldQueue); while (!readerSwitchSuccess) {
readerSwitched.await();
}
//前面的清空,刚好碰到reader要put最后一个,非阻塞式清空动作就有残留最后一个put
transferOldQueueRecordsToNewQueue(oldQueue); this.switchingQueue = false;
this.switchFinished.signalAll(); } finally {
switchingQueueLock.unlock();
} } catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
} private void transferOldQueueRecordsToNewQueue(ArrayBlockingQueue<Record> oldQueue)
throws InterruptedException {
List<Record> oldRecords = new ArrayList<Record>(oldQueue.size());
Record record = null;
while ((record = oldQueue.poll()) != null) {
oldRecords.add(record);
}
// 转移老队列剩下的记录到新队列
for (int i = 0; i < oldRecords.size(); i++) {
queue.put(oldRecords.get(i));
}
} public void close() {
this.closed = true;
switchingQueueLock.lock();
try {
//如果正在切换队列, 等切换做完才能,发送最后一个CLOSE
while (switchingQueue) {
switchFinished.await();
} this.queue.put(CLOSE_RECORD);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
finally{
switchingQueueLock.unlock();
}
} public void put(Record record) {
try { if (!queue.offer(record)) {
taskCounter.incrBufferFullCount();
if (!readerSwitchSuccess) {
notifyReaderSwitchSuccess();
}
queue.put(record);
}
taskCounter.incrReadCount();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
} private void notifyReaderSwitchSuccess() {
System.out.println("reader switch");
switchingQueueLock.lock();
try {
readerSwitchSuccess = true;
readerSwitched.signalAll();
} finally {
switchingQueueLock.unlock();
}
} public Record take() {
try { Record record = queue.poll();
//如果拿到了切换记录,则切换队列重试
if(record == SWITCH_QUEUE_RECORD){
if (!writerSwitchSuccess) {
notifyWriterSwitchSuccess();
}
record = queue.poll();
} if (record == null) {
taskCounter.incrBufferEmptyCount(); //调用take先检查是否正在切换,保证拿到新的队列
if (!writerSwitchSuccess) {
notifyWriterSwitchSuccess();
}
record = queue.take();
//如果很不幸刚好在take阻塞时候,切换,只能发送一个切换记录将其唤醒
if(record == SWITCH_QUEUE_RECORD){
if (!writerSwitchSuccess) {
notifyWriterSwitchSuccess();
}
record = queue.take();
}
}
if (record == CLOSE_RECORD) {
if (!writerSwitchSuccess) {
notifyWriterSwitchSuccess();
}
return null;
}
taskCounter.incrWriteCount();
return record;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
} private void notifyWriterSwitchSuccess() { System.out.println("writer switch");
switchingQueueLock.lock();
try {
writerSwitchSuccess = true;
writerSwitched.signalAll();
} finally {
switchingQueueLock.unlock();
} } }

java 可伸缩阻塞队列实现的更多相关文章

  1. Java多线程 阻塞队列和并发集合

    转载:大关的博客 Java多线程 阻塞队列和并发集合 本章主要探讨在多线程程序中与集合相关的内容.在多线程程序中,如果使用普通集合往往会造成数据错误,甚至造成程序崩溃.Java为多线程专门提供了特有的 ...

  2. Java集合--阻塞队列及各种实现的解析

    阻塞队列(Blocking Queue) 一.队列的定义 说的阻塞队列,就先了解下什么是队列,队列也是一种特殊的线性表结构,在线性表的基础上加了一条限制:那就是一端入队列,一端出队列,且需要遵循FIF ...

  3. Java:阻塞队列

    Java:阻塞队列 本笔记是根据bilibili上 尚硅谷 的课程 Java大厂面试题第二季 而做的笔记 1. 概述 概念 队列 队列就可以想成是一个数组,从一头进入,一头出去,排队买饭 阻塞队列 B ...

  4. JAVA可阻塞队列-ArrayBlockingQueue

    在前面的的文章,写了一个带有缓冲区的队列,是用JAVA的Lock下的Condition实现的,但是JAVA类中提供了这项功能,就是ArrayBlockingQueue, ArrayBlockingQu ...

  5. java 多线程阻塞队列 与 阻塞方法与和非阻塞方法

    Queue是什么 队列,是一种数据结构.除了优先级队列和LIFO队列外,队列都是以FIFO(先进先出)的方式对各个元素进行排序的.无论使用哪种排序方式,队列的头都是调用remove()或poll()移 ...

  6. Java -- 使用阻塞队列(BlockingQueue)控制线程通信

    BlockingQueeu接口是Queue的子接口,但是它的主要作用并不是作为容器,而是作为线程同步的工具. 特征: 当生产者线程试图向BlockingQueue中放入元素时,如果该队列已满,则该线程 ...

  7. Java并发--阻塞队列

    在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList),这些工具都为我们编写多线程程 ...

  8. Java中阻塞队列的使用

    http://blog.csdn.net/qq_35101189/article/details/56008342 在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如 ...

  9. java并发阻塞队列

    Java 并发编程利用 Condition 来实现阻塞队列 You are here:  开发&语言 - Java 文章 发布于 2017年06月26日  阅读 944 并发编程   什么是阻 ...

随机推荐

  1. POJ1639顶点度限制最小生成树

    题目:http://poj.org/problem?id=1639 见汪汀的<最小生成树问题的拓展>. 大体是先忽略与根节点相连的边,做一遍kruscal,得到几个连通块和一个根节点: 然 ...

  2. Angular 4.0 使用第三方类库

    使用第三方类库分为以下几步 1. 将第三方类库安装到本地 1) Jquery的命令 npm install jquery --save 2) 安装bootstrap 安装成功后,将文件下载到node_ ...

  3. 【shell】sed命令

    sed是一个很好的文件处理工具,本身是一个管道命令,主要是以行为单位进行处理,可以将数据行进行替换.删除.新增.选取等特定工作,下面先了解一下sed的用法sed命令行格式为:         sed ...

  4. 织梦dedecms模板制作时,循环递增autoindex使用方法整理

    文章转载:http://www.maihui123.com/dedecms/2012051964.html 织梦dedecms模板制作时,我们需要每循环一次,变量加一,这是就需要使用到autoinde ...

  5. nginx负载

    一. Nginx反向代理与负载均衡概念简介 • 严格地说,Nginx仅仅是作为Nginx Proxy反向代理使用的,因为这个反向代理功能表现的效果是负载均衡集群的效果,所以本文称之为Nginx负载均衡 ...

  6. 使用Golang进行性能分析(Profiling)

    转自:http://www.cppblog.com/sunicdavy/archive/2015/04/11/210308.html 本文介绍游戏服务器的性能分析, web服务器性能分析不在本文分析范 ...

  7. Z-tree 统计每一父节点的叶子节点数(看这一篇就够了)

    最近刚走出校园的我找到了第一份工作,在入职考核中就遇见了一道Z-tree的试题 这道题目本身是不难的,但是我第一次接触这个插件而且还把解决问题的方向搞错了,弄的我好几天都很难受. 弄得我都开始怀疑人生 ...

  8. Spark分析之MemoryStore

    private case class MemoryEntry(value: Any, size: Long, deserialized: Boolean) class MemoryStore(bloc ...

  9. Python3 os模块应用

    调用模块的实质是运行python代码,比如a.py文件里有函数f(),那么你在调用a模块的时候,实质是运行了a模块里的函数f(),这个时候内存里就有这个函数了,可以直接用,那是不是随便一个py类型的文 ...

  10. Oracle导出DMP文件的两种方法

    本文转载自:http://www.cnblogs.com/o-andy-o/archive/2013/06/05/3118611.html   导出: 方法一:利用PL/SQL Developer工具 ...