前言:大概认识了disruptor之后,我们来实现一个小型的disruptor。然后从这个小型的disruptor进行扩展。
使用网上的一个突破
head:代表我们要读的位置
tail:代表我们写的位置
bufferSize:代表一圈的大小
- 数据为空的条件 :head=tail
- 一个buffer是否满:head=tail%bufferSize+1(说明我tail已经跑了一圈,要追上你了)
有了这几个条件,我们来写一个简单的demo
当然这只是单线程模式下的例子:
public class DisMain {
/**
* 存放的环形队列
*/
private Object[] objects;
/**
* 尾部指针
*/
private int tail;
/**
* 头部指针
*/
private int head;
/**
* 环形大小
*/
private final static int ringBuffSie=16;
/**
* 判断环形是否为空
*
* @return
*/
public boolean isEmpty() {
if (tail == head) {
return true;
}
return false;
}
public boolean put(Object obj){
if(isFull()){
return false;
}else{
objects[tail%ringBuffSie]=obj;
tail++;
return true;
}
}
public Object get(){
if(isEmpty()){
return null;
}else{
Object obj = objects[head];
head++;
return obj;
}
}
/**
* 判断环形是否填满
*
* @return
*/
public boolean isFull() {
//现在的位置
int nowPro = tail - ringBuffSie;
if ((nowPro + 1) == head) {
return true;
}
return false;
}
/**
* 获取所有未消费的对象列表
*
* @return
*/
public List<Object> getObjects() {
List<Object> list = new ArrayList<>();
if (isEmpty()) {
//环形为空
return null;
}
//生产跑了多少圈
int proRoundSize = tail % ringBuffSie;
//消费跑了多少圈
int consumerRoundSize = head % ringBuffSie;
// 消费者和生产者跑了同样的圈数
if (proRoundSize == consumerRoundSize) {
for (int i = head + 1; i < tail; i++) {
list.add(objects[i]);
}
} else if (proRoundSize > consumerRoundSize) {
for (int i = head + 1; i < consumerRoundSize * ringBuffSie; i++) {
list.add(objects[i - consumerRoundSize * ringBuffSie]);
}
int cn = tail - proRoundSize * ringBuffSie;
for (int i = 0; i < cn; i++) {
list.add(objects[i]);
}
}
return list;
}
}