Created
April 7, 2016 03:21
-
-
Save liuzhengyang/24eaf4335cdb67563820fa11eeccaf70 to your computer and use it in GitHub Desktop.
stack concurrent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.lzy.algo.collect; | |
import java.util.concurrent.atomic.AtomicReference; | |
/** | |
* Description: Concurrent Stack | |
* | |
* @author liuzhengyang | |
* @version 1.0 | |
* @since 2016-04-07 | |
*/ | |
public class ConcurrentStack<E> { | |
private AtomicReference<Node<E>> top = new AtomicReference<>(); | |
public void push(E item) { | |
Node<E> newHead = new Node<>(item); | |
Node<E> old = null; | |
do { | |
old = top.get(); | |
newHead.next = old; | |
} while(!(top.compareAndSet(old, newHead))); | |
} | |
public E pop() { | |
Node<E> oldHead; | |
Node<E> newHead; | |
do { | |
oldHead = top.get(); | |
if (oldHead == null) { | |
return null; | |
} | |
newHead = oldHead.next; | |
} while (!(top.compareAndSet(oldHead, newHead))); | |
return oldHead.item; | |
} | |
public boolean isEmpty() { | |
return top.get() == null; | |
} | |
public E peek() { | |
if (top.get() == null) { | |
return null; | |
} else { | |
return top.get().item; | |
} | |
} | |
private static class Node<E> { | |
private E item; | |
private Node<E> next; | |
public Node(E item) { | |
this.item = item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment