其他分享
首页 > 其他分享> > disruptor第二弹(建基)

disruptor第二弹(建基)

作者:互联网

前言:大概认识了disruptor之后,我们来实现一个小型的disruptor。然后从这个小型的disruptor进行扩展。

使用网上的一个突破

 head:代表我们要读的位置

tail:代表我们写的位置

bufferSize:代表一圈的大小

  1. 数据为空的条件 :head=tail
  2. 一个buffer是否满:head=tail%bufferSize+1(说明我tail已经跑了一圈,要追上你了)

 

有了这几个条件,我们来写一个简单的demo

当然这只是单线程模式下的例子:

 

public class RingBuffer {

    private final static int bufferSize = 48;
    private String[] buffer = new String[bufferSize];
    private int head = 0;
    private int tail = 0;
    
    private Boolean empty() {
        return head == tail;
    }
    private Boolean full() {
        return (tail + 1) % bufferSize == head;
    }
    public Boolean put(String v) {
        if (full()) {
            return false;
        }
        buffer[tail] = v;
        tail = (tail + 1) % bufferSize;
        return true;
    }
    public String get() {
        if (empty()) {
            return null;
        }
        String result = buffer[head];
        head = (head + 1) % bufferSize;
        return result;
    }
    public String[] getAll() {
        if (empty()) {
            return new String[0];
        }
        //可以读的大小
        int cnt = head < tail ? tail - head : bufferSize - head + tail;
        String[] result = new String[cnt];
        if (head < tail) {
            for (int i = head; i < tail; i++) {
                result[i - head] = buffer[i];
            }
        } else {
            for (int i = head; i < bufferSize; i++) {
                result[i - head] = buffer[i];
            }
            for (int i = 0; i < tail; i++) {
                result[bufferSize - head + i] = buffer[i];
            }
        }
        head = tail;
        return result;
    }
}

 

标签:disruptor,head,return,String,buffer,第二,tail,建基,bufferSize
来源: https://blog.csdn.net/xiao__miao/article/details/101070255