Can somebody help me in writing a non-blocking, lock free stack implementation. Is it there in the Sun java implementation?
I was trying to write a thread safe Stack by putting a global lock on the whole stack data structure (it is costly) but it seems that it is possible to write a non-blocking, lock free stack.
An algorithm is called nonblocking if it is lock free and immune of deadlock.
public class MyConcurrentStack<T> {
private AtomicReference<Node> head = new AtomicReference<Node>();
public MyConcurrentStack() {
}
public void push(T t) {
if (t == null) {
return;
}
Node<T> n = new Node<T>(t);
Node<T> current;
do {
current = head.get();
n.setNext(current);
} while (!head.compareAndSet(current, n));
}
public T pop() {
Node<T> currentHead = null;
Node<T> futureHead = null;
do {
currentHead = head.get();
if (currentHead == null) {
return null;
}
futureHead = currentHead.next;
} while (!head.compareAndSet(currentHead, futureHead));
return currentHead.data;
}
/**
*
* @return null if no element present else return a element. it does not
* remove the element from the stack.
*/
public T peek() {
Node<T> n = head.get();
if (n == null) {
return null;
} else {
return n.data;
}
}
public boolean isEmpty() {
if (head.get() == null) {
return true;
}
return false;
}
private static class Node<T> {
private final T data;
private Node<T> next;
private Node(T data) {
this.data = data;
}
private void setNext(Node next) {
this.next = next;
}
}
}
concurrent stack java first google result
Queues
The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scalable thread-safe non-blocking FIFO queue. Five implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue. The different classes cover the most common usage contexts for producer-consumer, messaging, parallel tasking, and related concurrent designs. The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With