ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
(Generate patch)

Comparing jsr166/src/jsr166y/LinkedTransferQueue.java (file contents):
Revision 1.27 by jsr166, Sun Jul 26 05:55:34 2009 UTC vs.
Revision 1.35 by jsr166, Thu Jul 30 22:45:39 2009 UTC

# Line 10 | Line 10 | import java.util.concurrent.*;
10  
11   import java.util.AbstractQueue;
12   import java.util.Collection;
13 + import java.util.ConcurrentModificationException;
14   import java.util.Iterator;
15   import java.util.NoSuchElementException;
16 + import java.util.Queue;
17   import java.util.concurrent.locks.LockSupport;
18   import java.util.concurrent.atomic.AtomicReference;
17 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
19  
20   /**
21   * An unbounded {@linkplain TransferQueue} based on linked nodes.
# Line 115 | Line 116 | public class LinkedTransferQueue<E> exte
116              this.isData = isData;
117          }
118  
119 <        @SuppressWarnings("rawtypes")
120 <        static final AtomicReferenceFieldUpdater<Node, Node>
121 <            nextUpdater = AtomicReferenceFieldUpdater.newUpdater
122 <            (Node.class, Node.class, "next");
119 >        // Unsafe mechanics
120 >
121 >        private static final sun.misc.Unsafe UNSAFE = getUnsafe();
122 >        private static final long nextOffset =
123 >            objectFieldOffset(UNSAFE, "next", Node.class);
124  
125          final boolean casNext(Node<E> cmp, Node<E> val) {
126 <            return nextUpdater.compareAndSet(this, cmp, val);
126 >            return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
127          }
128  
129          final void clearNext() {
130 <            nextUpdater.lazySet(this, this);
130 >            UNSAFE.putOrderedObject(this, nextOffset, this);
131 >        }
132 >
133 >        /**
134 >         * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
135 >         * Replace with a simple call to Unsafe.getUnsafe when integrating
136 >         * into a jdk.
137 >         *
138 >         * @return a sun.misc.Unsafe
139 >         */
140 >        private static sun.misc.Unsafe getUnsafe() {
141 >            try {
142 >                return sun.misc.Unsafe.getUnsafe();
143 >            } catch (SecurityException se) {
144 >                try {
145 >                    return java.security.AccessController.doPrivileged
146 >                        (new java.security
147 >                         .PrivilegedExceptionAction<sun.misc.Unsafe>() {
148 >                            public sun.misc.Unsafe run() throws Exception {
149 >                                java.lang.reflect.Field f = sun.misc
150 >                                    .Unsafe.class.getDeclaredField("theUnsafe");
151 >                                f.setAccessible(true);
152 >                                return (sun.misc.Unsafe) f.get(null);
153 >                            }});
154 >                } catch (java.security.PrivilegedActionException e) {
155 >                    throw new RuntimeException("Could not initialize intrinsics",
156 >                                               e.getCause());
157 >                }
158 >            }
159          }
160  
161          private static final long serialVersionUID = -3375979862319811754L;
# Line 442 | Line 472 | public class LinkedTransferQueue<E> exte
472          addAll(c);
473      }
474  
475 <    public void put(E e) throws InterruptedException {
476 <        if (e == null) throw new NullPointerException();
477 <        if (Thread.interrupted()) throw new InterruptedException();
478 <        xfer(e, NOWAIT, 0);
475 >    /**
476 >     * Inserts the specified element at the tail of this queue.
477 >     * As the queue is unbounded, this method will never block.
478 >     *
479 >     * @throws NullPointerException if the specified element is null
480 >     */
481 >    public void put(E e) {
482 >        offer(e);
483      }
484  
485 <    public boolean offer(E e, long timeout, TimeUnit unit)
486 <        throws InterruptedException {
487 <        if (e == null) throw new NullPointerException();
488 <        if (Thread.interrupted()) throw new InterruptedException();
489 <        xfer(e, NOWAIT, 0);
490 <        return true;
485 >    /**
486 >     * Inserts the specified element at the tail of this queue.
487 >     * As the queue is unbounded, this method will never block or
488 >     * return {@code false}.
489 >     *
490 >     * @return {@code true} (as specified by
491 >     *  {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
492 >     * @throws NullPointerException if the specified element is null
493 >     */
494 >    public boolean offer(E e, long timeout, TimeUnit unit) {
495 >        return offer(e);
496      }
497  
498 +    /**
499 +     * Inserts the specified element at the tail of this queue.
500 +     * As the queue is unbounded, this method will never return {@code false}.
501 +     *
502 +     * @return {@code true} (as specified by
503 +     *         {@link BlockingQueue#offer(Object) BlockingQueue.offer})
504 +     * @throws NullPointerException if the specified element is null
505 +     */
506      public boolean offer(E e) {
507          if (e == null) throw new NullPointerException();
508          xfer(e, NOWAIT, 0);
509          return true;
510      }
511  
512 +    /**
513 +     * Inserts the specified element at the tail of this queue.
514 +     * As the queue is unbounded this method will never throw
515 +     * {@link IllegalStateException} or return {@code false}.
516 +     *
517 +     * @return {@code true} (as specified by {@link Collection#add})
518 +     * @throws NullPointerException if the specified element is null
519 +     */
520      public boolean add(E e) {
521 +        return offer(e);
522 +    }
523 +
524 +    /**
525 +     * Transfers the specified element immediately if there exists a
526 +     * consumer already waiting to receive it (in {@link #take} or
527 +     * timed {@link #poll(Object,long,TimeUnit) poll}), otherwise
528 +     * returning {@code false} without enqueuing the element.
529 +     *
530 +     * @throws NullPointerException if the specified element is null
531 +     */
532 +    public boolean tryTransfer(E e) {
533          if (e == null) throw new NullPointerException();
534 <        xfer(e, NOWAIT, 0);
468 <        return true;
534 >        return fulfill(e) != null;
535      }
536  
537 +    /**
538 +     * Inserts the specified element at the tail of this queue,
539 +     * waiting if necessary for the element to be received by a
540 +     * consumer invoking {@code take} or {@code poll}.
541 +     *
542 +     * @throws InterruptedException {@inheritDoc}
543 +     * @throws NullPointerException if the specified element is null
544 +     */
545      public void transfer(E e) throws InterruptedException {
546          if (e == null) throw new NullPointerException();
547          if (xfer(e, WAIT, 0) == null) {
# Line 476 | Line 550 | public class LinkedTransferQueue<E> exte
550          }
551      }
552  
553 +    /**
554 +     * Inserts the specified element at the tail of this queue,
555 +     * waiting up to the specified wait time for the element to be
556 +     * received by a consumer invoking {@code take} or {@code poll}.
557 +     *
558 +     * @throws InterruptedException {@inheritDoc}
559 +     * @throws NullPointerException if the specified element is null
560 +     */
561      public boolean tryTransfer(E e, long timeout, TimeUnit unit)
562          throws InterruptedException {
563          if (e == null) throw new NullPointerException();
# Line 486 | Line 568 | public class LinkedTransferQueue<E> exte
568          throw new InterruptedException();
569      }
570  
489    public boolean tryTransfer(E e) {
490        if (e == null) throw new NullPointerException();
491        return fulfill(e) != null;
492    }
493
571      public E take() throws InterruptedException {
572 <        Object e = xfer(null, WAIT, 0);
572 >        E e = xfer(null, WAIT, 0);
573          if (e != null)
574 <            return (E) e;
574 >            return e;
575          Thread.interrupted();
576          throw new InterruptedException();
577      }
578  
579 +    /**
580 +     * @throws InterruptedException {@inheritDoc}
581 +     */
582      public E poll(long timeout, TimeUnit unit) throws InterruptedException {
583 <        Object e = xfer(null, TIMEOUT, unit.toNanos(timeout));
583 >        E e = xfer(null, TIMEOUT, unit.toNanos(timeout));
584          if (e != null || !Thread.interrupted())
585 <            return (E) e;
585 >            return e;
586          throw new InterruptedException();
587      }
588  
# Line 510 | Line 590 | public class LinkedTransferQueue<E> exte
590          return fulfill(null);
591      }
592  
593 +    /**
594 +     * @throws NullPointerException     {@inheritDoc}
595 +     * @throws IllegalArgumentException {@inheritDoc}
596 +     */
597      public int drainTo(Collection<? super E> c) {
598          if (c == null)
599              throw new NullPointerException();
# Line 524 | Line 608 | public class LinkedTransferQueue<E> exte
608          return n;
609      }
610  
611 +    /**
612 +     * @throws NullPointerException     {@inheritDoc}
613 +     * @throws IllegalArgumentException {@inheritDoc}
614 +     */
615      public int drainTo(Collection<? super E> c, int maxElements) {
616          if (c == null)
617              throw new NullPointerException();
# Line 568 | Line 656 | public class LinkedTransferQueue<E> exte
656          }
657      }
658  
659 <
659 >    /**
660 >     * Returns an iterator over the elements in this queue in proper
661 >     * sequence, from head to tail.
662 >     *
663 >     * <p>The returned iterator is a "weakly consistent" iterator that
664 >     * will never throw
665 >     * {@link ConcurrentModificationException ConcurrentModificationException},
666 >     * and guarantees to traverse elements as they existed upon
667 >     * construction of the iterator, and may (but is not guaranteed
668 >     * to) reflect any modifications subsequent to construction.
669 >     *
670 >     * @return an iterator over the elements in this queue in proper sequence
671 >     */
672      public Iterator<E> iterator() {
673          return new Itr();
674      }
# Line 583 | Line 683 | public class LinkedTransferQueue<E> exte
683      class Itr implements Iterator<E> {
684          Node<E> next;        // node to return next
685          Node<E> pnext;       // predecessor of next
586        Node<E> snext;       // successor of next
686          Node<E> curr;        // last returned node, for remove()
687          Node<E> pcurr;       // predecessor of curr, for remove()
688 <        E nextItem;        // Cache of next item, once committed to in next
688 >        E nextItem;          // Cache of next item, once committed to in next
689  
690          Itr() {
691 <            findNext();
691 >            advance();
692          }
693  
694          /**
695 <         * Ensures next points to next valid node, or null if none.
695 >         * Moves to next valid node and returns item to return for
696 >         * next(), or null if no such.
697           */
698 <        void findNext() {
698 >        private E advance() {
699 >            pcurr = pnext;
700 >            curr = next;
701 >            E item = nextItem;
702 >
703              for (;;) {
704 <                Node<E> pred = pnext;
705 <                Node<E> q = next;
706 <                if (pred == null || pred == q) {
603 <                    pred = traversalHead();
604 <                    q = pred.next;
605 <                }
606 <                if (q == null || !q.isData) {
704 >                pnext = (next == null) ? traversalHead() : next;
705 >                next = pnext.next;
706 >                if (next == pnext) {
707                      next = null;
708 <                    return;
708 >                    continue;  // restart
709                  }
710 <                Object x = q.get();
711 <                Node<E> s = q.next;
712 <                if (x != null && q != x && q != s) {
710 >                if (next == null)
711 >                    break;
712 >                Object x = next.get();
713 >                if (x != null && x != next) {
714                      nextItem = (E) x;
715 <                    snext = s;
615 <                    pnext = pred;
616 <                    next = q;
617 <                    return;
715 >                    break;
716                  }
619                pnext = q;
620                next = s;
717              }
718 +            return item;
719          }
720  
721          public boolean hasNext() {
# Line 626 | Line 723 | public class LinkedTransferQueue<E> exte
723          }
724  
725          public E next() {
726 <            if (next == null) throw new NoSuchElementException();
727 <            pcurr = pnext;
728 <            curr = next;
632 <            pnext = next;
633 <            next = snext;
634 <            E x = nextItem;
635 <            findNext();
636 <            return x;
726 >            if (next == null)
727 >                throw new NoSuchElementException();
728 >            return advance();
729          }
730  
731          public void remove() {
# Line 703 | Line 795 | public class LinkedTransferQueue<E> exte
795       * @return the number of elements in this queue
796       */
797      public int size() {
798 <        int count = 0;
799 <        Node<E> h = traversalHead();
800 <        for (Node<E> p = h.next; p != null && p.isData; p = p.next) {
801 <            Object x = p.get();
802 <            if (x != null && x != p) {
803 <                if (++count == Integer.MAX_VALUE) // saturated
798 >        for (;;) {
799 >            int count = 0;
800 >            Node<E> pred = traversalHead();
801 >            for (;;) {
802 >                Node<E> q = pred.next;
803 >                if (q == pred) // restart
804                      break;
805 +                if (q == null || !q.isData)
806 +                    return count;
807 +                Object x = q.get();
808 +                if (x != null && x != q) {
809 +                    if (++count == Integer.MAX_VALUE) // saturated
810 +                        return count;
811 +                }
812 +                pred = q;
813              }
814          }
715        return count;
815      }
816  
817      public int getWaitingConsumerCount() {
818 <        int count = 0;
819 <        Node<E> h = traversalHead();
820 <        for (Node<E> p = h.next; p != null && !p.isData; p = p.next) {
821 <            if (p.get() == null) {
822 <                if (++count == Integer.MAX_VALUE)
818 >        // converse of size -- count valid non-data nodes
819 >        for (;;) {
820 >            int count = 0;
821 >            Node<E> pred = traversalHead();
822 >            for (;;) {
823 >                Node<E> q = pred.next;
824 >                if (q == pred) // restart
825                      break;
826 +                if (q == null || q.isData)
827 +                    return count;
828 +                Object x = q.get();
829 +                if (x == null) {
830 +                    if (++count == Integer.MAX_VALUE) // saturated
831 +                        return count;
832 +                }
833 +                pred = q;
834              }
835          }
727        return count;
728    }
729
730    public int remainingCapacity() {
731        return Integer.MAX_VALUE;
836      }
837  
838      public boolean remove(Object o) {
# Line 738 | Line 842 | public class LinkedTransferQueue<E> exte
842              Node<E> pred = traversalHead();
843              for (;;) {
844                  Node<E> q = pred.next;
741                if (q == null || !q.isData)
742                    return false;
845                  if (q == pred) // restart
846                      break;
847 +                if (q == null || !q.isData)
848 +                    return false;
849                  Object x = q.get();
850                  if (x != null && x != q && o.equals(x) &&
851                      q.compareAndSet(x, q)) {
# Line 754 | Line 858 | public class LinkedTransferQueue<E> exte
858      }
859  
860      /**
861 +     * Always returns {@code Integer.MAX_VALUE} because a
862 +     * {@code LinkedTransferQueue} is not capacity constrained.
863 +     *
864 +     * @return {@code Integer.MAX_VALUE} (as specified by
865 +     *         {@link BlockingQueue#remainingCapacity()})
866 +     */
867 +    public int remainingCapacity() {
868 +        return Integer.MAX_VALUE;
869 +    }
870 +
871 +    /**
872       * Save the state to a stream (that is, serialize it).
873       *
874       * @serialData All of the elements (each an {@code E}) in
# Line 799 | Line 914 | public class LinkedTransferQueue<E> exte
914                                   new PaddedAtomicReference<Node<E>>(null));
915      }
916  
917 <    // Unsafe mechanics for jsr166y 3rd party package.
917 >    // Unsafe mechanics
918 >
919 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
920 >    private static final long headOffset =
921 >        objectFieldOffset(UNSAFE, "head", LinkedTransferQueue.class);
922 >    private static final long tailOffset =
923 >        objectFieldOffset(UNSAFE, "tail", LinkedTransferQueue.class);
924 >    private static final long cleanMeOffset =
925 >        objectFieldOffset(UNSAFE, "cleanMe", LinkedTransferQueue.class);
926 >
927 >
928 >    static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
929 >                                  String field, Class<?> klazz) {
930 >        try {
931 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
932 >        } catch (NoSuchFieldException e) {
933 >            // Convert Exception to corresponding Error
934 >            NoSuchFieldError error = new NoSuchFieldError(field);
935 >            error.initCause(e);
936 >            throw error;
937 >        }
938 >    }
939 >
940 >    /**
941 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
942 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
943 >     * into a jdk.
944 >     *
945 >     * @return a sun.misc.Unsafe
946 >     */
947      private static sun.misc.Unsafe getUnsafe() {
948          try {
949              return sun.misc.Unsafe.getUnsafe();
950          } catch (SecurityException se) {
951              try {
952                  return java.security.AccessController.doPrivileged
953 <                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
953 >                    (new java.security
954 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
955                          public sun.misc.Unsafe run() throws Exception {
956 <                            return getUnsafeByReflection();
956 >                            java.lang.reflect.Field f = sun.misc
957 >                                .Unsafe.class.getDeclaredField("theUnsafe");
958 >                            f.setAccessible(true);
959 >                            return (sun.misc.Unsafe) f.get(null);
960                          }});
961              } catch (java.security.PrivilegedActionException e) {
962                  throw new RuntimeException("Could not initialize intrinsics",
# Line 816 | Line 964 | public class LinkedTransferQueue<E> exte
964              }
965          }
966      }
819
820    private static sun.misc.Unsafe getUnsafeByReflection()
821            throws NoSuchFieldException, IllegalAccessException {
822        java.lang.reflect.Field f =
823            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
824        f.setAccessible(true);
825        return (sun.misc.Unsafe) f.get(null);
826    }
827
828    private static long fieldOffset(String fieldName, Class<?> klazz) {
829        try {
830            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
831        } catch (NoSuchFieldException e) {
832            // Convert Exception to Error
833            NoSuchFieldError error = new NoSuchFieldError(fieldName);
834            error.initCause(e);
835            throw error;
836        }
837    }
838
839    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
840    private static final long headOffset =
841        fieldOffset("head", LinkedTransferQueue.class);
842    private static final long tailOffset =
843        fieldOffset("tail", LinkedTransferQueue.class);
844    private static final long cleanMeOffset =
845        fieldOffset("cleanMe", LinkedTransferQueue.class);
846
967   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines