Esempio n. 1
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. 2
0
  public Session take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      while (active) {
        Session first = queue.peek();
        if (first == null) {
          available.await();
        } else {
          long delay = getDelay(first, TimeUnit.NANOSECONDS);
          if (delay > 0) {
            available.awaitNanos(delay);
          } else {
            Session x = queue.poll();
            assert x != null;
            if (queue.size() != 0) {
              available.signalAll(); // wake up other takers
            }
            return x;
          }
        }
      }

      throw new InterruptedException("Session queue is stopping");
    } finally {
      lock.unlock();
    }
  }
  public Events<Event> get(Position start, int batchSize, long timeout, TimeUnit unit)
      throws InterruptedException, CanalStoreException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (checkUnGetSlotAt((LogPosition) start, batchSize)) {
          return doGet(start, batchSize);
        }

        if (nanos <= 0) {
          // 如果时间到了,有多少取多少
          return doGet(start, batchSize);
        }

        try {
          nanos = notEmpty.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notEmpty.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
  public boolean put(List<Event> data, long timeout, TimeUnit unit)
      throws InterruptedException, CanalStoreException {
    if (data == null || data.isEmpty()) {
      return true;
    }

    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (checkFreeSlotAt(putSequence.get() + data.size())) {
          doPut(data);
          return true;
        }
        if (nanos <= 0) {
          return false;
        }

        try {
          nanos = notFull.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notFull.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
 public RunnableScheduledFuture<?> take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) available.await();
       else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         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 && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
 public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
     throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         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 && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
Esempio n. 7
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();
   }
 }
  public E take() throws InterruptedException {
    Node<E> x;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
      try {
        while (count.get() == 0) notEmpty.await();
      } catch (InterruptedException ie) {
        notEmpty.signal(); // propagate to a non-interrupted thread
        throw ie;
      }

      x = extract();
      if (count.getAndDecrement() > 1) notEmpty.signal();
    } finally {
      takeLock.unlock();
    }

    E result = x.item;

    // temporary clearence
    x.item = null;
    x.next = null;

    return result;
  }
Esempio n. 9
0
 /** Acquire one permit from the semaphore in a manner that can be interrupted. */
 public void acquire() throws InterruptedException {
   // TODO - you fill in here.
   lock.lockInterruptibly();
   try {
     while (availablePermits() == 0) permitAvailable.await();
     numAvailablePermits--;
   } finally {
     lock.unlock();
   }
 }
Esempio n. 10
0
 public T take() throws InterruptedException {
   lock.lockInterruptibly();
   try {
     while (count == 0) {
       notEmpty.await();
     }
     return dequeue();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 11
0
 public void put(T t) throws InterruptedException {
   lock.lockInterruptibly();
   try {
     while (count == getCapacity()) {
       notFull.await();
     }
     enqueue(t);
   } finally {
     lock.unlock();
   }
 }
 @Override
 public E takeFirst() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   E result;
   try {
     while ((result = removeAt(0)) == null) notEmpty.await();
   } finally {
     lock.unlock();
   }
   return result;
 }
Esempio n. 13
0
 /** Acquire one permit from the semaphore in a manner that can be interrupted. */
 public void acquire() throws InterruptedException {
   // TODO - you fill in here.
   reentrantLock.lockInterruptibly();
   try {
     while (permits == 0) {
       condition.await();
     }
     permits--;
   } finally {
     reentrantLock.unlock();
   }
 }
 @Override
 public E pollFirst(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   E result;
   try {
     while ((result = removeAt(0)) == null && nanos > 0) nanos = notEmpty.awaitNanos(nanos);
   } finally {
     lock.unlock();
   }
   return result;
 }
 public void insert(E obj) throws Exception {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     while (this.capacity == this.queue.size()) {
       this.notFull.await();
     }
     this.queue.add(obj);
     this.notEmpty.signal();
   } finally {
     lock.unlock();
   }
 }
 @Override
 public E takeLast() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   E result;
   try {
     int indexMax = indexOfLargerChild(deque, size, 0, comparator);
     int indexRemove = indexMax > 0 ? indexMax : 0;
     while ((result = removeAt(indexRemove)) == null) notEmpty.await();
   } finally {
     lock.unlock();
   }
   return result;
 }
 public E remove() throws Exception {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     while (queue.size() == 0) {
       this.notEmpty.await();
     }
     E result = this.queue.poll();
     this.notFull.signal();
     return result;
   } finally {
     lock.unlock();
   }
 }
Esempio n. 18
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();
   }
 }
 /**
  * Inserts the specified element at the tail of this queue, waiting for space to become available
  * if the queue is full.
  *
  * @throws InterruptedException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  */
 public void put(E e) throws InterruptedException {
   if (e == null) throw new NullPointerException();
   final E[] items = this.items;
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     try {
       while (count == items.length) notFull.await();
     } catch (InterruptedException ie) {
       notFull.signal(); // propagate to non-interrupted thread
       throw ie;
     }
     insert(e);
   } finally {
     lock.unlock();
   }
 }
  public Events<Event> get(Position start, int batchSize)
      throws InterruptedException, CanalStoreException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      try {
        while (!checkUnGetSlotAt((LogPosition) start, batchSize)) notEmpty.await();
      } catch (InterruptedException ie) {
        notEmpty.signal(); // propagate to non-interrupted thread
        throw ie;
      }

      return doGet(start, batchSize);
    } finally {
      lock.unlock();
    }
  }
Esempio n. 22
0
  public boolean enterIfInterruptibly(Monitor.Guard var1) throws InterruptedException {
    if (var1.monitor != this) {
      throw new IllegalMonitorStateException();
    } else {
      ReentrantLock var2 = this.lock;
      var2.lockInterruptibly();
      boolean var3 = false;

      boolean var4;
      try {
        var4 = var3 = var1.isSatisfied();
      } finally {
        if (!var3) {
          var2.unlock();
        }
      }

      return var4;
    }
  }
  @Override
  public void resume() throws EventException {

    try {
      lock.lockInterruptibly();
    } catch (Exception ne) {
      throw new EventException(ne);
    }

    try {
      awaitPaused = false;
      // We don't have to actually start anything again because the getMessage(...) call reconnects
      // automatically.
      paused.signalAll();
      logger.info(getName() + " running");
      System.out.println(getName() + " running");

    } finally {
      lock.unlock();
    }
  }
  /**
   * Wait on the latest, previously enlisted element to get forced or failed.
   *
   * <p>Important: A call to this method measures the storage of all enlisted element that were
   * enlisted in the current thread under the assumption that elements are stored in the order they
   * were placed in the queue.
   *
   * @return returns true if the force operation succeeded and false if an IO error was reported.
   */
  public boolean waitOnEnlisted() {
    long enlistedElementNumber =
        pendingRecordsQueue.getMaxElementSequenceNumberForCurrentThread(true);

    try {
      // Wait until we have our entry forced (may not require a wait at all if it already happened).
      forceLock.lockInterruptibly();
      try {
        while (enlistedElementNumber > latestForcedElement.get()) {
          if (verifyIsInFailedRange(enlistedElementNumber)) return false;

          if (log.isDebugEnabled()) {
            log.debug(
                "Waiting until entry with sequence " + enlistedElementNumber + " was forced.");
          }
          performedForce.await();
        }
      } finally {
        forceLock.unlock();
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new RuntimeException(e);
    }

    // Check if we had an exception.
    if (verifyIsInFailedRange(enlistedElementNumber)) {
      return false;
    } else {
      if (log.isDebugEnabled()) {
        log.debug(
            "Entry with sequence "
                + enlistedElementNumber
                + " was successfully forced (force ranges up to "
                + latestForcedElement.get()
                + ").");
      }
      return true;
    }
  }
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       if (count != 0) {
         E x = extract();
         return x;
       }
       if (nanos <= 0) return null;
       try {
         nanos = notEmpty.awaitNanos(nanos);
       } catch (InterruptedException ie) {
         notEmpty.signal(); // propagate to non-interrupted thread
         throw ie;
       }
     }
   } finally {
     lock.unlock();
   }
 }
Esempio n. 26
0
  public void enterWhen(Monitor.Guard var1) throws InterruptedException {
    if (var1.monitor != this) {
      throw new IllegalMonitorStateException();
    } else {
      ReentrantLock var2 = this.lock;
      boolean var3 = var2.isHeldByCurrentThread();
      var2.lockInterruptibly();
      boolean var4 = false;

      try {
        if (!var1.isSatisfied()) {
          this.await(var1, var3);
        }

        var4 = true;
      } finally {
        if (!var4) {
          this.leave();
        }
      }
    }
  }
Esempio n. 27
0
  /**
   * <pre>
   *  Makes it possible to test invalid usages of {@link Locale#getDefault()} in a synchronized
   *  manner making sure that test cases don't fail suddenly when they are run concurrently.
   *  I.e a pipelined version of {@link Locale#getDefault()}.
   *
   * <b>Note:</b> Don't forget to call {@link #resetDefaultLocale()} when you're done with using
   * the {@link Locale#getDefault()} method. Otherwise other threads waiting to use it may starve.
   *
   * @param locale the locale {@link Locale#getDefault()} should return
   * @throws InterruptedException if the current thread is interrupted
   * @return the previous default locale
   * </pre>
   */
  public static Locale setDefault(Locale locale) throws InterruptedException {
    checkNotNull(locale);
    // Allow the same thread to change the locale during its "period" without locking
    if (!LOCK.isHeldByCurrentThread()) {
      try {
        LOCK.lockInterruptibly();
        defaultLocale = Locale.getDefault();
      } catch (InterruptedException interrupt) {
        throw new InterruptedException(
            format(
                "%s waited on %s to finish using %s but got interrupted",
                currentThread().getName(), LOCK, Locale.getDefault()));
      }
    }

    try {
      Locale.setDefault(locale);
    } catch (SecurityException e) {
      LOCK.unlock(); // Let someone else try again
      throw e;
    }
    return defaultLocale;
  }
  @Override
  public void pause() throws EventException {

    if (!isActive()) return; // Nothing to pause
    try {
      lock.lockInterruptibly();
    } catch (Exception ne) {
      throw new EventException(ne);
    }

    try {
      awaitPaused = true;
      if (mconsumer != null) mconsumer.close();
      mconsumer = null; // Force unpaused consumers to make a new connection.
      logger.info(getName() + " is paused");
      System.out.println(getName() + " is paused");

    } catch (Exception ne) {
      throw new EventException(ne);
    } finally {
      lock.unlock();
    }
  }
  /**
   * Inserts the specified element at the tail of this queue, waiting up to the specified wait time
   * for space to become available if the queue is full.
   *
   * @throws InterruptedException {@inheritDoc}
   * @throws NullPointerException {@inheritDoc}
   */
  public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {

    if (e == null) throw new NullPointerException();
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (count != items.length) {
          insert(e);
          return true;
        }
        if (nanos <= 0) return false;
        try {
          nanos = notFull.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notFull.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
  public void put(List<Event> data) throws InterruptedException, CanalStoreException {
    if (data == null || data.isEmpty()) {
      return;
    }

    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      try {
        while (!checkFreeSlotAt(putSequence.get() + data.size())) { // 检查是否有空位
          notFull.await(); // wait until not full
        }
      } catch (InterruptedException ie) {
        notFull.signal(); // propagate to non-interrupted thread
        throw ie;
      }
      doPut(data);
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
    } finally {
      lock.unlock();
    }
  }