public class Queue { private Long[] data; private int size = 0, head = 0, tail = 0; public Queue(int size) { this.data = new Long[size]; this.size = size; } public boolean add(Long element) { if ((tail + 1) % size == head) return false; data[tail] = element; tail = (tail + 1) % size; return true; } public Long poll() { if (head == tail) return null; long ret = data[head]; head = (head + 1) % size; return ret; } } public class Producer { private Queue queue; public Producer(Queue queue) { this.queue = queue; } public void produce(Long data) throws InterruptedException { while (!queue.add(data)) { Thread.sleep(100); } } } public class Consumer { private Queue queue; public Consumer(Queue queue) { this.queue = queue; } public void comsume() throws InterruptedException { while (true) { Long data = queue.poll(); if (data == null) { Thread.sleep(100); } else { // TODO:...消费数据的业务逻辑... } } } }
Disruptor 采用的是 RingBuffer 和 AvailableBuffer 这两个结构来实现上面的功能。
disruptor使用环的数据结构,内存连续,初始化时就申请并设置对象,将原本队列的头尾节点锁的争用转化为cas操作,并利用Java对象填充,解决cache line伪共享问题。
数据结构与算法简记--剖析高性能队列Disruptor背后的数据结构和算法
原文:https://www.cnblogs.com/wod-Y/p/12215309.html