利用环形队列+CAS实现无锁队列

利用环形队列+CAS实现无锁队列

优点:

1.保证元素的先进先出

2.元素空间可以重复利用,因为是环形的。

3.为多线程数据通信提供了一种高效的机制,比BlockingQueue速度要快。

下面提供一种Java实现:

public class LockFreeQueue {
  private AtomicReferenceArray atomicReferenceArray;
  priviate final Integer EMPTY = null;
  private AtomicInteger head,tail;
  public LockFreeQueue(int size) {
    //空出一个位置 用于判断队列满或空 tail==head时为空 (tail+1)%len==head为满
  	atomicReferenceArray = new AtomicRefrenceArray(new Integer[size + 1]);
    head = new AtomicInteger(0);
    tail = new AtomicInteger(0);
  }
  
  public boolean add(Integer element) {
  	int index = (tail.get() + 1% atomicReferenceArray.length();
    if (index == head.get()) {
      System.out.println("队列已满")return false;
    }
    while(!atomicReferenceArray.compareAndSet(index,EMPTY,element)) {
      return add(element);
	}
    tail.incrementAndGet();
    System.out.println("入队成功")return true;
  }
  
  public Integer poll() {
    if (tail.get() == head.get()) {
      System.out.println("队列已空");
      return false;
    }
    int index = (head.get() + 1) % atomicReferenceArray.length();
    Integer ele = atomicReferenceArray.get(index);
    if (ele == null) {
      return poll();
    }
    while (!atomicReferenceArray.compareAndSet(index,ele,EMPTY)) {
      return poll();
	}
    head.incrementAndGet();
    System.out.println("出对成功");
    return ele;
  }
}

你可能感兴趣的:(Java并发)