stack
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| stack [2007/10/28 15:28] – created franck | stack [2007/10/28 16:43] (current) – franck | ||
|---|---|---|---|
| Line 160: | Line 160: | ||
| </ | </ | ||
| + | The third implementation does not use any locking. | ||
| + | |||
| + | <code java> | ||
| + | import java.util.concurrent.atomic.*; | ||
| + | |||
| + | public class Stack3 implements Stack | ||
| + | { | ||
| + | private volatile AtomicReference< | ||
| + | |||
| + | /** | ||
| + | * Creates an empty stack. | ||
| + | */ | ||
| + | public Stack3() | ||
| + | { | ||
| + | this.top = new AtomicReference< | ||
| + | } | ||
| + | |||
| + | public Integer pop() throws EmptyException | ||
| + | { | ||
| + | Node node; | ||
| + | do | ||
| + | { | ||
| + | node = this.top.get(); | ||
| + | if (node == null) | ||
| + | { | ||
| + | throw new EmptyException(); | ||
| + | } | ||
| + | } | ||
| + | while (!this.top.compareAndSet(node, | ||
| + | return node.getElement(); | ||
| + | } | ||
| + | |||
| + | public void push(Integer element) | ||
| + | { | ||
| + | Node node = new Node(element, | ||
| + | do | ||
| + | { | ||
| + | node.setNext(this.top.get()); | ||
| + | } | ||
| + | while (!this.top.compareAndSet(node.getNext(), | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Also the fourth implementation does not use any locking. | ||
| + | |||
| + | <code java> | ||
| + | import java.util.concurrent.atomic.*; | ||
| + | |||
| + | public class Stack4 implements Stack | ||
| + | { | ||
| + | private volatile Node top; | ||
| + | |||
| + | private static final AtomicReferenceFieldUpdater< | ||
| + | 4.class, Node.class, " | ||
| + | |||
| + | /** | ||
| + | * Creates an empty stack. | ||
| + | */ | ||
| + | public Stack4() | ||
| + | { | ||
| + | this.top = null; | ||
| + | } | ||
| + | |||
| + | public Integer pop() throws EmptyException | ||
| + | { | ||
| + | Node node; | ||
| + | do | ||
| + | { | ||
| + | node = this.top; | ||
| + | if (node == null) | ||
| + | { | ||
| + | throw new EmptyException(); | ||
| + | } | ||
| + | } while (!Stack4.topUpdater.compareAndSet(this, | ||
| + | return node.getElement(); | ||
| + | } | ||
| + | |||
| + | public void push(Integer element) | ||
| + | { | ||
| + | Node node = new Node(element, | ||
| + | do | ||
| + | { | ||
| + | node.setNext(this.top); | ||
| + | } | ||
| + | while (!Stack4.topUpdater.compareAndSet(this, | ||
| + | } | ||
| + | } | ||
| + | </ | ||
stack.1193585300.txt.gz · Last modified: by franck
