java 无锁队列实现_java – 这是(无锁)队列实现线程安全吗?

我试图在

Java中创建一个无锁队列的实现,主要用于个人学习.队列应该是一个通用的队列,允许任意数量的读者和/或作者同时进行.

你能否回顾一下,并提出任何改进/问题你找到?

谢谢.

import java.util.concurrent.atomic.AtomicReference;

public class LockFreeQueue {

private static class Node {

E value;

volatile Node next;

Node(E value) {

this.value = value;

}

}

private AtomicReference> head,tail;

public LockFreeQueue() {

// have both head and tail point to a dummy node

Node dummyNode = new Node(null);

head = new AtomicReference>(dummyNode);

tail = new AtomicReference>(dummyNode);

}

/**

* Puts an object at the end of the queue.

*/

public void putObject(T value) {

Node newNode = new Node(value);

Node prevTailNode = tail.getAndSet(newNode);

prevTailNode.next = newNode;

}

/**

* Gets an object from the beginning of the queue. The object is removed

* from the queue. If there are no objects in the queue,returns null.

*/

public T getObject() {

Node headNode,valueNode;

// move head node to the next node using atomic semantics

// as long as next node is not null

do {

headNode = head.get();

valueNode = headNode.next;

// try until the whole loop executes pseudo-atomically

// (i.e. unaffected by modifications done by other threads)

} while (valueNode != null && !head.compareAndSet(headNode,valueNode));

T value = (valueNode != null ? valueNode.value : null);

// release the value pointed to by head,keeping the head node dummy

if (valueNode != null)

valueNode.value = null;

return value;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值