/**
  * @throws UnsupportedOperationException {@inheritDoc}
  * @throws ClassCastException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  * @throws IllegalArgumentException {@inheritDoc}
  */
 public int drainTo(Collection<? super E> c, int maxElements) {
   if (c == null) throw new NullPointerException();
   if (c == this) throw new IllegalArgumentException();
   if (maxElements <= 0) return 0;
   final E[] items = this.items;
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     int i = takeIndex;
     int n = 0;
     int sz = count;
     int max = (maxElements < count) ? maxElements : count;
     while (n < max) {
       c.add(items[i]);
       items[i] = null;
       i = inc(i);
       ++n;
     }
     if (n > 0) {
       count -= n;
       takeIndex = i;
       notFull.signalAll();
     }
     return n;
   } finally {
     lock.unlock();
   }
 }
 /**
  * Creates an <tt>ArrayBlockingQueue</tt> with the given (fixed) capacity and the specified access
  * policy.
  *
  * @param capacity the capacity of this queue
  * @param fair if <tt>true</tt> then queue accesses for threads blocked on insertion or removal,
  *     are processed in FIFO order; if <tt>false</tt> the access order is unspecified.
  * @throws IllegalArgumentException if <tt>capacity</tt> is less than 1
  */
 public ArrayBlockingQueue(int capacity, boolean fair) {
   if (capacity <= 0) throw new IllegalArgumentException();
   this.items = (E[]) new Object[capacity];
   lock = new ReentrantLock(fair);
   notEmpty = lock.newCondition();
   notFull = lock.newCondition();
 }
Esempio n. 3
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay > 0) {
           if (nanos <= 0) return null;
           if (delay > nanos) delay = nanos;
           long timeLeft = available.awaitNanos(delay);
           nanos -= delay - timeLeft;
         } else {
           E x = q.poll();
           assert x != null;
           if (q.size() != 0) available.signalAll();
           return x;
         }
       }
     }
   } finally {
     lock.unlock();
   }
 }
Esempio n. 4
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue.
  *
  * @return the head of this queue
  * @throws InterruptedException {@inheritDoc}
  */
 public E take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) available.await();
       else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
Esempio n. 5
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         if (nanos <= 0) return null;
         if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos);
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             long timeLeft = available.awaitNanos(delay);
             nanos -= delay - timeLeft;
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
Esempio n. 6
0
 /**
  * Atomically removes all of the elements from this delay queue. The queue will be empty after
  * this call returns. Elements with an unexpired delay are not waited for; they are simply
  * discarded from the queue.
  */
 public void clear() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     q.clear();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 7
0
 /**
  * Retrieves, but does not remove, the head of this queue, or returns <tt>null</tt> if this queue
  * is empty. Unlike <tt>poll</tt>, if no expired elements are available in the queue, this method
  * returns the element that will expire next, if one exists.
  *
  * @return the head of this queue, or <tt>null</tt> if this queue is empty.
  */
 public E peek() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return q.peek();
   } finally {
     lock.unlock();
   }
 }
 /**
  * Returns the number of additional elements that this queue can ideally (in the absence of memory
  * or resource constraints) accept without blocking. This is always equal to the initial capacity
  * of this queue less the current <tt>size</tt> of this queue.
  *
  * <p>Note that you <em>cannot</em> always tell if an attempt to insert an element will succeed by
  * inspecting <tt>remainingCapacity</tt> because it may be the case that another thread is about
  * to insert or remove an element.
  */
 public int remainingCapacity() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return items.length - count;
   } finally {
     lock.unlock();
   }
 }
 public E peek() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return (count == 0) ? null : items[takeIndex];
   } finally {
     lock.unlock();
   }
 }
Esempio n. 10
0
 /**
  * Returns an array containing all of the elements in this queue; the runtime type of the returned
  * array is that of the specified array. The returned array elements are in no particular order.
  * If the queue fits in the specified array, it is returned therein. Otherwise, a new array is
  * allocated with the runtime type of the specified array and the size of this queue.
  *
  * <p>If this queue fits in the specified array with room to spare (i.e., the array has more
  * elements than this queue), the element in the array immediately following the end of the queue
  * is set to <tt>null</tt>.
  *
  * <p>Like the {@link #toArray()} method, this method acts as bridge between array-based and
  * collection-based APIs. Further, this method allows precise control over the runtime type of the
  * output array, and may, under certain circumstances, be used to save allocation costs.
  *
  * <p>The following code can be used to dump a delay queue into a newly allocated array of
  * <tt>Delayed</tt>:
  *
  * <pre>
  *     Delayed[] a = q.toArray(new Delayed[0]);</pre>
  *
  * Note that <tt>toArray(new Object[0])</tt> is identical in function to <tt>toArray()</tt>.
  *
  * @param a the array into which the elements of the queue are to be stored, if it is big enough;
  *     otherwise, a new array of the same runtime type is allocated for this purpose
  * @return an array containing all of the elements in this queue
  * @throws ArrayStoreException if the runtime type of the specified array is not a supertype of
  *     the runtime type of every element in this queue
  * @throws NullPointerException if the specified array is null
  */
 public <T> T[] toArray(T[] a) {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return q.toArray(a);
   } finally {
     lock.unlock();
   }
 }
Esempio n. 11
0
 /**
  * Removes a single instance of the specified element from this queue, if it is present, whether
  * or not it has expired.
  */
 public boolean remove(Object o) {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return q.remove(o);
   } finally {
     lock.unlock();
   }
 }
Esempio n. 12
0
    public static void main(String[] args) throws Throwable {
      final ReentrantLock lock = new ReentrantLock();
      lock.lock();

      final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
      final ReentrantReadWriteLock.ReadLock readLock = rwlock.readLock();
      final ReentrantReadWriteLock.WriteLock writeLock = rwlock.writeLock();
      rwlock.writeLock().lock();

      final BlockingQueue<Object> q = new LinkedBlockingQueue<Object>();
      final Semaphore fairSem = new Semaphore(0, true);
      final Semaphore unfairSem = new Semaphore(0, false);
      // final int threads =
      // rnd.nextInt(Runtime.getRuntime().availableProcessors() + 1) + 1;
      final int threads = 3;
      // On Linux, this test runs very slowly for some reason,
      // so use a smaller number of iterations.
      // Solaris can handle 1 << 18.
      // On the other hand, jmap is much slower on Solaris...
      final int iterations = 1 << 8;
      final CyclicBarrier cb = new CyclicBarrier(threads + 1);

      for (int i = 0; i < threads; i++)
        new Thread() {
          public void run() {
            try {
              final Random rnd = new Random();
              for (int j = 0; j < iterations; j++) {
                if (j == iterations / 10 || j == iterations - 1) {
                  cb.await(); // Quiesce
                  cb.await(); // Resume
                }
                // int t = rnd.nextInt(2000);
                int t = rnd.nextInt(900);
                check(!lock.tryLock(t, NANOSECONDS));
                check(!readLock.tryLock(t, NANOSECONDS));
                check(!writeLock.tryLock(t, NANOSECONDS));
                equal(null, q.poll(t, NANOSECONDS));
                check(!fairSem.tryAcquire(t, NANOSECONDS));
                check(!unfairSem.tryAcquire(t, NANOSECONDS));
              }
            } catch (Throwable t) {
              unexpected(t);
            }
          }
        }.start();

      cb.await(); // Quiesce
      rendezvousChild(); // Measure
      cb.await(); // Resume

      cb.await(); // Quiesce
      rendezvousChild(); // Measure
      cb.await(); // Resume

      System.exit(failed);
    }
 public String toString() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return super.toString();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 14
0
 /**
  * Returns an array containing all of the elements in this queue. The returned array elements are
  * in no particular order.
  *
  * <p>The returned array will be "safe" in that no references to it are maintained by this queue.
  * (In other words, this method must allocate a new array). The caller is thus free to modify the
  * returned array.
  *
  * <p>This method acts as bridge between array-based and collection-based APIs.
  *
  * @return an array containing all of the elements in this queue
  */
 public Object[] toArray() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return q.toArray();
   } finally {
     lock.unlock();
   }
 }
 /**
  * Returns an iterator over the elements in this queue in proper sequence. The returned
  * <tt>Iterator</tt> is a "weakly consistent" iterator that will never throw {@link
  * ConcurrentModificationException}, and guarantees to traverse elements as they existed upon
  * construction of the iterator, and may (but is not guaranteed to) reflect any modifications
  * subsequent to construction.
  *
  * @return an iterator over the elements in this queue in proper sequence
  */
 public Iterator<E> iterator() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return new Itr();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 16
0
 public int size() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return q.size();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 17
0
 /**
  * Retrieves and removes the head of this queue, or returns <tt>null</tt> if this queue has no
  * elements with an expired delay.
  *
  * @return the head of this queue, or <tt>null</tt> if this queue has no elements with an expired
  *     delay
  */
 public E poll() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     E first = q.peek();
     if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) return null;
     else return q.poll();
   } finally {
     lock.unlock();
   }
 }
 public E poll() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     if (count == 0) return null;
     E x = extract();
     return x;
   } finally {
     lock.unlock();
   }
 }
Esempio n. 19
0
 /**
  * Inserts the specified element into this delay queue.
  *
  * @param e the element to add
  * @return <tt>true</tt>
  * @throws NullPointerException if the specified element is null
  */
 public boolean offer(E e) {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     E first = q.peek();
     q.offer(e);
     if (first == null || e.compareTo(first) < 0) available.signalAll();
     return true;
   } finally {
     lock.unlock();
   }
 }
Esempio n. 20
0
 /**
  * Inserts the specified element into this delay queue.
  *
  * @param e the element to add
  * @return <tt>true</tt>
  * @throws NullPointerException if the specified element is null
  */
 public boolean offer(E e) {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     q.offer(e);
     if (q.peek() == e) {
       leader = null;
       available.signal();
     }
     return true;
   } finally {
     lock.unlock();
   }
 }
 public E next() {
   final ReentrantLock lock = ArrayBlockingQueue.this.lock;
   lock.lock();
   try {
     if (nextIndex < 0) throw new NoSuchElementException();
     lastRet = nextIndex;
     E x = nextItem;
     nextIndex = inc(nextIndex);
     checkNext();
     return x;
   } finally {
     lock.unlock();
   }
 }
 /**
  * Inserts the specified element at the tail of this queue if it is possible to do so immediately
  * without exceeding the queue's capacity, returning <tt>true</tt> upon success and <tt>false</tt>
  * if this queue is full. This method is generally preferable to method {@link #add}, which can
  * fail to insert an element only by throwing an exception.
  *
  * @throws NullPointerException if the specified element is null
  */
 public boolean offer(E e) {
   if (e == null) throw new NullPointerException();
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     if (count == items.length) return false;
     else {
       insert(e);
       return true;
     }
   } finally {
     lock.unlock();
   }
 }
Esempio n. 23
0
  @Override
  public void setChainHead(StoredBlock chainHead) throws BlockStoreException {
    final MappedByteBuffer buffer = this.buffer;
    if (buffer == null) throw new BlockStoreException("Store closed");

    lock.lock();
    try {
      lastChainHead = chainHead;
      byte[] headHash = chainHead.getHeader().getHash().getBytes();
      buffer.position(8);
      buffer.put(headHash);
    } finally {
      lock.unlock();
    }
  }
Esempio n. 24
0
 private void initNewStore(NetworkParameters params) throws Exception {
   byte[] header;
   header = HEADER_MAGIC.getBytes("US-ASCII");
   buffer.put(header);
   // Insert the genesis block.
   lock.lock();
   try {
     setRingCursor(buffer, FILE_PROLOGUE_BYTES);
   } finally {
     lock.unlock();
   }
   Block genesis = params.getGenesisBlock().cloneAsHeader();
   StoredBlock storedGenesis = new StoredBlock(genesis, genesis.getWork(), 0);
   put(storedGenesis);
   setChainHead(storedGenesis);
 }
Esempio n. 25
0
 /**
  * Retrieves and removes the head of this queue, or returns <tt>null</tt> if this queue has no
  * elements with an expired delay.
  *
  * @return the head of this queue, or <tt>null</tt> if this queue has no elements with an expired
  *     delay
  */
 public E poll() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     E first = q.peek();
     if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) return null;
     else {
       E x = q.poll();
       assert x != null;
       if (q.size() != 0) available.signalAll();
       return x;
     }
   } finally {
     lock.unlock();
   }
 }
Esempio n. 26
0
 public final Object call() throws Exception {
   barrier.await();
   int sum = v;
   int x = 0;
   int n = ITERS;
   while (n-- > 0) {
     lock.lockInterruptibly();
     try {
       v = x = LoopHelpers.compute1(v);
     } finally {
       lock.unlock();
     }
     sum += LoopHelpers.compute2(LoopHelpers.compute2(x));
   }
   return new Integer(sum);
 }
 public E take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     try {
       while (count == 0) notEmpty.await();
     } catch (InterruptedException ie) {
       notEmpty.signal(); // propagate to non-interrupted thread
       throw ie;
     }
     E x = extract();
     return x;
   } finally {
     lock.unlock();
   }
 }
 /**
  * Returns <tt>true</tt> if this queue contains the specified element. More formally, returns
  * <tt>true</tt> if and only if this queue contains at least one element <tt>e</tt> such that
  * <tt>o.equals(e)</tt>.
  *
  * @param o object to be checked for containment in this queue
  * @return <tt>true</tt> if this queue contains the specified element
  */
 public boolean contains(Object o) {
   if (o == null) return false;
   final E[] items = this.items;
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     int i = takeIndex;
     int k = 0;
     while (k++ < count) {
       if (o.equals(items[i])) return true;
       i = inc(i);
     }
     return false;
   } finally {
     lock.unlock();
   }
 }
 /**
  * Returns an array containing all of the elements in this queue, in proper sequence.
  *
  * <p>The returned array will be "safe" in that no references to it are maintained by this queue.
  * (In other words, this method must allocate a new array). The caller is thus free to modify the
  * returned array.
  *
  * <p>This method acts as bridge between array-based and collection-based APIs.
  *
  * @return an array containing all of the elements in this queue
  */
 public Object[] toArray() {
   final E[] items = this.items;
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     Object[] a = new Object[count];
     int k = 0;
     int i = takeIndex;
     while (k < count) {
       a[k++] = items[i];
       i = inc(i);
     }
     return a;
   } finally {
     lock.unlock();
   }
 }
    public void remove() {
      final ReentrantLock lock = ArrayBlockingQueue.this.lock;
      lock.lock();
      try {
        int i = lastRet;
        if (i == -1) throw new IllegalStateException();
        lastRet = -1;

        int ti = takeIndex;
        removeAt(i);
        // back up cursor (reset to front if was first element)
        nextIndex = (i == ti) ? takeIndex : i;
        checkNext();
      } finally {
        lock.unlock();
      }
    }