无锁环形队列

作者: nextbang | 来源:发表于2017-01-23 23:23 被阅读188次

并发编程中,经常会遇到资源竞争问题,而保持竞争资源的正确使用,可以通过锁的方式,但synchronized block对性能的影响很大,本文要说的 ** 无锁环形队列 ** 通过利用CAS特性,可以使锁的力度降到最低。

下面实例代码分为三部分

  1. RingBuffer 环形队列
  2. ProductThread 生产者线程
  3. ConsumeThread 消费者线程

** RingBuffer.java **

package com.nextbang.queue;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by nextbang on 17/1/23.
 */
public class RingBuffer {
    private static AtomicInteger productIndex = new AtomicInteger(0);

    private static AtomicInteger consumeIndex = new AtomicInteger(0);

    private static int MAX_LENGTH = 4;

    private static String[] dataArr = new String[MAX_LENGTH];

    private static final int maxSpinNums = 1000;

    public static boolean write(String content) {
        // 获取写入位置
        int oldWriteIndex = productIndex.get();

        // 追上一圈则写入失败
        if ((oldWriteIndex - consumeIndex.get()) >= MAX_LENGTH) {
            return false;
        }

        int indexAfterWrite = oldWriteIndex + 1;
        if (indexAfterWrite > Integer.MAX_VALUE) {
            indexAfterWrite = 0;
        }

        int spinNums = 0;
        for (;;) {
            if (spinNums++ >= maxSpinNums) {
                return false;
            }
            if (productIndex.compareAndSet(oldWriteIndex, indexAfterWrite)) {
                dataArr[oldWriteIndex & (MAX_LENGTH - 1)] = content;
                break;
            }
        }

        return true;
    }

    public static String read() {
        // 获取读取位置
        int oldReadIndex = consumeIndex.get();

        if (productIndex.get() <= oldReadIndex) {
            return null;
        }

        int indexAfterRead = oldReadIndex + 1;
        if (indexAfterRead > Integer.MAX_VALUE) {
            indexAfterRead = 0;
        }

        for (;;) {
            if (consumeIndex.compareAndSet(oldReadIndex, indexAfterRead)) {
                return dataArr[oldReadIndex & (MAX_LENGTH - 1)];
            }
        }
    }


    public static void main(String[] args) {
        System.out.println(RingBuffer.write("a"));
        System.out.println(RingBuffer.read());
    }
}

** ProductThread **

package com.nextbang.queue;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by nextbang on 17/1/23.
 */
public class ProductThread extends Thread{

    private String content=null;

    public ProductThread(String content){
        this.content = content;
    }

    public void run(){
        System.out.println(RingBuffer.write(content));
    }

    public static void main(String[] args){
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for(int i=0;i<10;i++){
            executorService.execute(new ProductThread("" + i));
        }
    }
}

** ConsumeThread **

package com.nextbang.queue;

import com.sun.tools.internal.xjc.reader.Ring;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by nextbang on 17/1/23.
 */
public class ConsumeThread extends Thread{

    public void run(){
        System.out.println(RingBuffer.read());
    }

    public static void main(String[] args){
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(new ConsumeThread());
    }
}

代码github地址
https://github.com/nextbang/unlock_queue

参考文章
http://coolshell.cn/articles/8239.html
http://hellosure.iteye.com/blog/1126541
http://shanshanpt.github.io/2016/11/01/disruptor.html

相关文章

  • 无锁环形队列

    并发编程中,经常会遇到资源竞争问题,而保持竞争资源的正确使用,可以通过锁的方式,但synchronized blo...

  • rte_ring

    dpdk的rte_ring实现的无锁队列,支持多生产者多消费者; 实现上使用了cas原子操作,结构是环形队列,思路...

  • DPDK中无锁环形队列实现

    因为最近在研究高性能方面的技术,突然想起上一份工作从事抗D的项目,在项目中使用到的dpdk组件,其中之一有无锁相关...

  • 无锁数组队列

    无锁数组队列

  • 无锁队列

    简介 无锁队列是lock-free中最基本的数据结构,一般应用场景是资源分配,比如TimerId的分配,Worke...

  • 无锁队列

    rte_ring 关键点 无锁: rte_atomic32_cmpset 直到成功(CAS)环: 总长度c...

  • 数组实现环形队列

    利用数组结构在队列的基础下用取模算法来实现环形队列。 环形队列拥有复用功能。 主要算法思想:1)front指向队列...

  • 2020-11-10-数据结构与算法-14(队列scala版)

    1.队列 非环形实现 2.队列环形版 核心思想: 用%来模拟循环(rear +1) /maxsize = firs...

  • 环形队列

    写完这篇文章想着以后尽量(应该说一定)使用现在正在使用的LPC系列的单片机写程序,其实内心感觉还是LPC做的相当完...

  • 环形队列

    1、概念 环形队列是一个最为简单的数据结构,底层用数组组成,然后逻辑上数组首尾相连。虽然他的结构极为简单,但是用处...

网友评论

    本文标题:无锁环形队列

    本文链接:https://www.haomeiwen.com/subject/tejabttx.html