User Tools

Site Tools


stack

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
stack [2007/10/28 16:36] franckstack [2007/10/28 16:43] (current) franck
Line 160: Line 160:
 </code> </code>
  
 +The third implementation does not use any locking.  We exploit the class AtomicReference.
  
 +<code java>
 +import java.util.concurrent.atomic.*;
 +
 +public class Stack3 implements Stack
 +{
 +  private volatile AtomicReference<Node> top;
 +
 +  /**
 +   * Creates an empty stack.
 +   */
 +  public Stack3()
 +  {
 +    this.top = new AtomicReference<Node>();
 +  }
 +
 +  public Integer pop() throws EmptyException
 +  {
 +    Node node;
 +    do
 +    {
 +      node = this.top.get();
 +      if (node == null)
 +      {
 +        throw new EmptyException();
 +      }
 +    }
 +    while (!this.top.compareAndSet(node, node.getNext()));
 +    return node.getElement();
 +  }
 +
 +  public void push(Integer element)
 +  {
 +    Node node = new Node(element, null);
 +    do
 +    {
 +      node.setNext(this.top.get());
 +    }
 +    while (!this.top.compareAndSet(node.getNext(), node));
 +  }
 +}
 +</code>
 +
 +Also the fourth implementation does not use any locking.  This time we exploit the class AtomicReferenceFieldUpdater.
  
 <code java> <code java>
stack.1193589398.txt.gz · Last modified: 2007/10/28 16:36 by franck

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki