高性能队列-Disruptor--简介(1)

背景

Disruptor是英国外汇交易公司LMAX开发的一个高性能队列,研发的初衷是解决内存队列的延迟问题(在性能测试中发现竟然与I/O操作处于同样的数量级)。基于Disruptor开发的系统单线程能支撑每秒600万订单,2010年在QCon演讲后,获得了业界关注.

锁和CAS

在进入探讨disruptor之前,我们选择几个java内置的队列来做以下几组测试:
LinkedBlockingQueue 使用链表结构 通过锁保证操作线程安全
ConcurrentLinkedQueue 使用链表结构 通过CAS保证操作线程安全
ArrayBlockingQueue 使用数组的方式实现 通过锁保证操作线程安全

测试方法:启动50个线程,往同一个队列里面插入元素.每个现场插入500000个元素.

测试代码如下:

public class QueueTest {
    //static Queue<Integer> queue = new LinkedBlockingQueue<Integer>();
    static Queue<Integer> queue = new ArrayBlockingQueue<Integer>(50000000);
    // static Queue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
    static producerThread[] threads=new producerThread[50];
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //new customerThread().start();
        long begintime = Calendar.getInstance().getTimeInMillis();
        for(int i=0;i<threads.length;i++){
            threads[i]=new producerThread();
        }

        for(int i=0;i<threads.length;i++){
            threads[i].start();
        }
        for(int i=0;i<threads.length;i++){
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("消耗时间:"
                + (Calendar.getInstance().getTimeInMillis() - begintime));
    }

    static class producerThread extends Thread {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            for (int i = 0; i< 500000; i++) {
                queue.add(i);
            }

        }

    }

}

测试结果:
LinkedBlockingQueue :20964 ms
ConcurrentLinkedQueue:12010 ms
ArrayBlockingQueue :5941 ms

通过上面的测试,我们可以得出结论:

  1. 数组优于链表
  2. CAS优于锁

    我们做个猜想,如果有一种队列,是通过数组的方式实现,而且又不用锁,那岂不是速度很快?

猜你喜欢

转载自blog.csdn.net/xfks55/article/details/69950689