使用链表实现 链表中时刻保有两个元素。在任何并发的操作情况下,只要保证赋值是原子操作,即可保证无锁的并发安全。可能导致消费延迟到下一次申请,但是不会出现未消费产品。
可能有分析错误 求指正
package gt.lockFreeList;
public class Node<T> {
private T data;
private Node<T> next = null;
public Node() {
}
public Node(T t) {
// TODO Auto-generated constructor stub
data = t;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
@SuppressWarnings("unchecked")
Node<T> n = ((Node<T>) obj);
return data.equals(n.data) && (next == n.next);// next pointer should
// have a same memory
// pointing
}
}
package gt.lockFreeList;
public class List<T> {
private Node<T> head = new Node<T>();
private Node<T> tail = new Node<T>();
private boolean used[] = { true, true };
public List() {
head.setNext(tail);
}
public void put(T t) {
Node<T> temp = new Node<T>(t);
tail.setNext(temp);
tail = temp;
if (used[0]) {
pop();
used[1] = false;
}
}
public T get() {
T t = null;
while (canPop() && t == null) {// when there are more than two elements
// in the list
if (used[0]) {
pop();
} else {
t = pop();
}
}
if (t == null) {// when there are exactly two elements in the list keep
// them as placeholder
if (used[0]) {
if (used[1]) {
} else {
used[1] = true;
t = head.getNext().getData();
}
} else {
used[0] = true;
t = head.getData();
}
}
return t;
}
public T pop() {
Node<T> h = head;
head = h.getNext();
used[0] = used[1];
return h.getData();
}
public boolean canPop() {
return !(head.getNext() == tail);
}
}
可能有分析错误 求指正