Java Code Examples for java.util.concurrent.TimeUnit.toNanos()

The following are Jave code examples for showing how to use toNanos() of the java.util.concurrent.TimeUnit class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: googles-monorepo-demo   File: InterruptionUtil.java   Source Code and License Vote up 6 votes
private static void joinUninterruptibly(
    Thread thread, long timeout, TimeUnit unit) {
  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;

    while (true) {
      try {
        // TimeUnit.timedJoin() treats negative timeouts just like zero.
        NANOSECONDS.timedJoin(thread, remainingNanos);
        return;
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 2
Project: sstable-adaptor   File: SimpleCondition.java   Source Code and License Vote up 6 votes
public boolean await(long time, TimeUnit unit) throws InterruptedException
{
    if (isSignaled())
        return true;
    long start = System.nanoTime();
    long until = start + unit.toNanos(time);
    if (waiting == null)
        waitingUpdater.compareAndSet(this, null, new WaitQueue());
    WaitQueue.Signal s = waiting.register();
    if (isSignaled())
    {
        s.cancel();
        return true;
    }
    return s.awaitUntil(until) || isSignaled();
}
 
Example 3
Project: OpenJSharp   File: StampedLock.java   Source Code and License Vote up 6 votes
/**
 * Non-exclusively acquires the lock if it is available within the
 * given time and the current thread has not been interrupted.
 * Behavior under timeout and interruption matches that specified
 * for method {@link Lock#tryLock(long,TimeUnit)}.
 *
 * @param time the maximum time to wait for the lock
 * @param unit the time unit of the {@code time} argument
 * @return a stamp that can be used to unlock or convert mode,
 * or zero if the lock is not available
 * @throws InterruptedException if the current thread is interrupted
 * before acquiring the lock
 */
public long tryReadLock(long time, TimeUnit unit)
    throws InterruptedException {
    long s, m, next, deadline;
    long nanos = unit.toNanos(time);
    if (!Thread.interrupted()) {
        if ((m = (s = state) & ABITS) != WBIT) {
            if (m < RFULL) {
                if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
                    return next;
            }
            else if ((next = tryIncReaderOverflow(s)) != 0L)
                return next;
        }
        if (nanos <= 0L)
            return 0L;
        if ((deadline = System.nanoTime() + nanos) == 0L)
            deadline = 1L;
        if ((next = acquireRead(true, deadline)) != INTERRUPTED)
            return next;
    }
    throw new InterruptedException();
}
 
Example 4
Project: GifImageLoader   File: LinkedBlockingDeque.java   Source Code and License Vote up 6 votes
public E pollLast(long timeout, TimeUnit unit)
        throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        E x;
        while ((x = unlinkLast()) == null) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        return x;
    } finally {
        lock.unlock();
    }
}
 
Example 5
Project: uavstack   File: QueueWorkerThreadPoolExecutor.java   Source Code and License Vote up 6 votes
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {

    long nanos = unit.toNanos(timeout);
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        for (;;) {
            if (runStateAtLeast(ctl.get(), TERMINATED))
                return true;
            if (nanos <= 0)
                return false;
            nanos = termination.awaitNanos(nanos);
        }
    }
    finally {
        mainLock.unlock();
    }
}
 
Example 6
Project: ditb   File: BoundedPriorityBlockingQueue.java   Source Code and License Vote up 6 votes
public E poll(long timeout, TimeUnit unit)
    throws InterruptedException {
  long nanos = unit.toNanos(timeout);
  lock.lockInterruptibly();
  E result = null;
  try {
    while (queue.size() == 0 && nanos > 0) {
      nanos = notEmpty.awaitNanos(nanos);
    }
    if (queue.size() > 0) {
      result = queue.poll();
    }
    notFull.signal();
  } finally {
    lock.unlock();
  }
  return result;
}
 
Example 7
Project: openjdk-jdk10   File: StampedLock.java   Source Code and License Vote up 6 votes
/**
 * Non-exclusively acquires the lock if it is available within the
 * given time and the current thread has not been interrupted.
 * Behavior under timeout and interruption matches that specified
 * for method {@link Lock#tryLock(long,TimeUnit)}.
 *
 * @param time the maximum time to wait for the lock
 * @param unit the time unit of the {@code time} argument
 * @return a read stamp that can be used to unlock or convert mode,
 * or zero if the lock is not available
 * @throws InterruptedException if the current thread is interrupted
 * before acquiring the lock
 */
@ReservedStackAccess
public long tryReadLock(long time, TimeUnit unit)
    throws InterruptedException {
    long s, m, next, deadline;
    long nanos = unit.toNanos(time);
    if (!Thread.interrupted()) {
        if ((m = (s = state) & ABITS) != WBIT) {
            if (m < RFULL) {
                if (casState(s, next = s + RUNIT))
                    return next;
            }
            else if ((next = tryIncReaderOverflow(s)) != 0L)
                return next;
        }
        if (nanos <= 0L)
            return 0L;
        if ((deadline = System.nanoTime() + nanos) == 0L)
            deadline = 1L;
        if ((next = acquireRead(true, deadline)) != INTERRUPTED)
            return next;
    }
    throw new InterruptedException();
}
 
Example 8
Project: Cable-Android   File: LinkedBlockingDeque.java   Source Code and License Vote up 6 votes
/**
 * @throws NullPointerException {@inheritDoc}
 * @throws InterruptedException {@inheritDoc}
 */
public boolean offerFirst(E e, long timeout, TimeUnit unit)
    throws InterruptedException {
    if (e == null) throw new NullPointerException();
    Node<E> node = new Node<E>(e);
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (!linkFirst(node)) {
            if (nanos <= 0)
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        return true;
    } finally {
        lock.unlock();
    }
}
 
Example 9
Project: jsf-sdk   File: SmoothTokenBucketLimiter.java   Source Code and License Vote up 6 votes
private void uninterruptibleSleep(long sleepTime,TimeUnit unit){
    boolean interrupted = false;
    try {
        long remainingNanos = unit.toNanos(sleepTime);
        long end = System.nanoTime() + remainingNanos;
        while (true){
            try {
                NANOSECONDS.sleep(remainingNanos);
                return;
            } catch (InterruptedException e) {
                interrupted = true;
                remainingNanos = end - System.nanoTime();
            }
        }
    } finally {
        if (interrupted){
            Thread.currentThread().interrupt();
        }
    }
}
 
Example 10
Project: ditb   File: StealJobQueue.java   Source Code and License Vote up 6 votes
@Override
public T poll(long timeout, TimeUnit unit) throws InterruptedException {
  long nanos = unit.toNanos(timeout);
  lock.lockInterruptibly();
  try {
    while (true) {
      T retVal = this.poll();
      if (retVal == null) {
        retVal = stealFromQueue.poll();
      }
      if (retVal == null) {
        if (nanos <= 0)
          return null;
        nanos = notEmpty.awaitNanos(nanos);
      } else {
        return retVal;
      }
    }
  } finally {
    lock.unlock();
  }
}
 
Example 11
Project: oneops   File: MetricsElasticsearchModule.java   Source Code and License Vote up 5 votes
private TimerSerializer(TimeUnit rateUnit, TimeUnit durationUnit, String timestampFieldname) {
    super(JsonTimer.class);
    this.timestampFieldname = timestampFieldname;
    this.rateUnit = calculateRateUnit(rateUnit, "calls");
    this.rateFactor = rateUnit.toSeconds(1);
    this.durationUnit = durationUnit.toString().toLowerCase(Locale.US);
    this.durationFactor = 1.0 / durationUnit.toNanos(1);
}
 
Example 12
Project: GitHub   File: ConnectionPool.java   Source Code and License Vote up 5 votes
public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
  this.maxIdleConnections = maxIdleConnections;
  this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration);

  // Put a floor on the keep alive duration, otherwise cleanup will spin loop.
  if (keepAliveDuration <= 0) {
    throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration);
  }
}
 
Example 13
Project: aos-MediaLib   File: ThreadGate.java   Source Code and License Vote up 5 votes
/**
 * @return OPEN or BROKEN if gate was passed in specified time. CLOSED if gate didn't
 * open in time. And finally InterruptedException in case the thread was interrupted
 * during waiting (which also means that the gate was not passed).
 */
public int pass(long time, @NonNull TimeUnit unit) throws InterruptedException {
    mLock.lock();
    try {
        if (mState == CLOSED) {
            // even for 0 / negative time.. ?!
            waitAction();

            // wait for either OPEN or BROKEN, see doc on spurious wakeups why this is in a loop
            long remainingNanos = unit.toNanos(time);
            while (mState == CLOSED) {
                if (remainingNanos <= 0) {
                    break;
                }
                remainingNanos = mOpenState.awaitNanos(remainingNanos);
            }
        }

        // not returning mState here since actions can potentially change mState
        switch (mState) {
            case OPEN:
                passOpenAction();
                return OPEN;
            case BROKEN:
                passBrokenAction();
                return BROKEN;
            case CLOSED:
                // no action?
                return CLOSED;
            default:
                throw new IllegalStateException("This is supposed to be unreachable.");
        }
    } finally {
        mLock.unlock();
    }

}
 
Example 14
Project: pugtsdb   File: ScheduledThreadPool.java   Source Code and License Vote up 5 votes
public ScheduledFuture<?>scheduleAtFixedRate(Runnable command, long initialDelayValue, TimeUnit initialDelayUnit, long periodValue, ChronoUnit periodUnit) {
    long initialDelayNanos = initialDelayUnit.toNanos(initialDelayValue);

    switch (periodUnit) {
        case NANOS:
            return scheduleAtFixedRate(command, initialDelayNanos, periodValue, NANOSECONDS);
        case MICROS:
            return scheduleAtFixedRate(command, initialDelayNanos, TimeUnit.MICROSECONDS.toNanos(periodValue), NANOSECONDS);
        case MILLIS:
            return scheduleAtFixedRate(command, initialDelayNanos, TimeUnit.MILLISECONDS.toNanos(periodValue), NANOSECONDS);
        case SECONDS:
            return scheduleAtFixedRate(command, initialDelayNanos, TimeUnit.SECONDS.toNanos(periodValue), NANOSECONDS);
        case MINUTES:
            return scheduleAtFixedRate(command, initialDelayNanos, TimeUnit.MINUTES.toNanos(periodValue), NANOSECONDS);
        case HOURS:
            return scheduleAtFixedRate(command, initialDelayNanos, TimeUnit.HOURS.toNanos(periodValue), NANOSECONDS);
        default:
            Trigger trigger = new ChronoTrigger(periodValue, periodUnit);

            Runnable runnable = () -> {
                if (trigger.runNow()) {
                    command.run();
                }
            };

            return scheduleAtFixedRate(runnable, initialDelayNanos, TimeUnit.HOURS.toNanos(1), NANOSECONDS);
    }

}
 
Example 15
Project: nifi-android-s2s   File: PropertiesSiteToSiteClientConfigFactory.java   Source Code and License Vote up 5 votes
protected Long getDurationNanos(Properties properties, String propBase) {
    String durationString = StringUtils.emptyToNull(properties.getProperty(propBase));
    if (durationString == null) {
        return null;
    }
    long duration = Long.parseLong(durationString);
    String unitString = StringUtils.emptyToNull(properties.getProperty(propBase + ".unit"));
    TimeUnit timeUnit = TimeUnit.MILLISECONDS;
    if (unitString != null) {
        timeUnit = TimeUnit.valueOf(unitString);
    }
    return timeUnit.toNanos(duration);
}
 
Example 16
Project: util4j   File: YieldingWaitConditionStrategy.java   Source Code and License Vote up 5 votes
@Override
public <T> T waitFor(WaitCondition<T> waitCondition, long timeOut, TimeUnit unit) throws InterruptedException {
   	long endTime=System.nanoTime()+unit.toNanos(timeOut);
   	int counter = SPIN_TRIES;
   	while (!waitCondition.isComplete())
       {
   		if(System.nanoTime()>=endTime)
   		{
   			break;
   		}
           counter = applyWaitMethod(counter);//等待
       }
   	return waitCondition.getAttach();
}
 
Example 17
Project: ditb   File: TimeoutBlockingQueue.java   Source Code and License Vote up 4 votes
private long getNanosTimeout(final E obj) {
  TimeUnit unit = timeoutRetriever.getTimeUnit(obj);
  long timeout = timeoutRetriever.getTimeout(obj);
  return unit.toNanos(timeout);
}
 
Example 18
Project: googles-monorepo-demo   File: AbstractFuture.java   Source Code and License Vote up 4 votes
/**
 * {@inheritDoc}
 *
 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
 * current thread is interrupted before or during the call, even if the value is already
 * available.
 *
 * @throws InterruptedException if the current thread was interrupted before or during the call
 *     (optional but recommended).
 * @throws CancellationException {@inheritDoc}
 */
@CanIgnoreReturnValue
@Override
public V get(long timeout, TimeUnit unit)
    throws InterruptedException, TimeoutException, ExecutionException {
  // NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop
  // at the bottom and throw a timeoutexception.
  long remainingNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit.
  if (Thread.interrupted()) {
    throw new InterruptedException();
  }
  Object localValue = value;
  if (localValue != null & !(localValue instanceof SetFuture)) {
    return getDoneValue(localValue);
  }
  // we delay calling nanoTime until we know we will need to either park or spin
  final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0;
  long_wait_loop:
  if (remainingNanos >= SPIN_THRESHOLD_NANOS) {
    Waiter oldHead = waiters;
    if (oldHead != Waiter.TOMBSTONE) {
      Waiter node = new Waiter();
      do {
        node.setNext(oldHead);
        if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
          while (true) {
            LockSupport.parkNanos(this, remainingNanos);
            // Check interruption first, if we woke up due to interruption we need to honor that.
            if (Thread.interrupted()) {
              removeWaiter(node);
              throw new InterruptedException();
            }

            // Otherwise re-read and check doneness. If we loop then it must have been a spurious
            // wakeup
            localValue = value;
            if (localValue != null & !(localValue instanceof SetFuture)) {
              return getDoneValue(localValue);
            }

            // timed out?
            remainingNanos = endNanos - System.nanoTime();
            if (remainingNanos < SPIN_THRESHOLD_NANOS) {
              // Remove the waiter, one way or another we are done parking this thread.
              removeWaiter(node);
              break long_wait_loop; // jump down to the busy wait loop
            }
          }
        }
        oldHead = waiters; // re-read and loop.
      } while (oldHead != Waiter.TOMBSTONE);
    }
    // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
    // waiter.
    return getDoneValue(value);
  }
  // If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the
  // waiters list
  while (remainingNanos > 0) {
    localValue = value;
    if (localValue != null & !(localValue instanceof SetFuture)) {
      return getDoneValue(localValue);
    }
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
    remainingNanos = endNanos - System.nanoTime();
  }
  throw new TimeoutException();
}
 
Example 19
Project: OpenJSharp   File: Phaser.java   Source Code and License Vote up 4 votes
/**
 * Awaits the phase of this phaser to advance from the given phase
 * value or the given timeout to elapse, throwing {@code
 * InterruptedException} if interrupted while waiting, or
 * returning immediately if the current phase is not equal to the
 * given phase value or this phaser is terminated.
 *
 * @param phase an arrival phase number, or negative value if
 * terminated; this argument is normally the value returned by a
 * previous call to {@code arrive} or {@code arriveAndDeregister}.
 * @param timeout how long to wait before giving up, in units of
 *        {@code unit}
 * @param unit a {@code TimeUnit} determining how to interpret the
 *        {@code timeout} parameter
 * @return the next arrival phase number, or the argument if it is
 * negative, or the (negative) {@linkplain #getPhase() current phase}
 * if terminated
 * @throws InterruptedException if thread interrupted while waiting
 * @throws TimeoutException if timed out while waiting
 */
public int awaitAdvanceInterruptibly(int phase,
                                     long timeout, TimeUnit unit)
    throws InterruptedException, TimeoutException {
    long nanos = unit.toNanos(timeout);
    final Phaser root = this.root;
    long s = (root == this) ? state : reconcileState();
    int p = (int)(s >>> PHASE_SHIFT);
    if (phase < 0)
        return phase;
    if (p == phase) {
        QNode node = new QNode(this, phase, true, true, nanos);
        p = root.internalAwaitAdvance(phase, node);
        if (node.wasInterrupted)
            throw new InterruptedException();
        else if (p == phase)
            throw new TimeoutException();
    }
    return p;
}
 
Example 20
Project: guava-mock   File: CacheBuilder.java   Source Code and License Vote up 3 votes
/**
 * Specifies that each entry should be automatically removed from the cache once a fixed duration
 * has elapsed after the entry's creation, or the most recent replacement of its value.
 *
 * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
 * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
 * useful in testing, or to disable caching temporarily without a code change.
 *
 * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
 * write operations. Expired entries are cleaned up as part of the routine maintenance described
 * in the class javadoc.
 *
 * @param duration the length of time after an entry is created that it should be automatically
 *     removed
 * @param unit the unit that {@code duration} is expressed in
 * @return this {@code CacheBuilder} instance (for chaining)
 * @throws IllegalArgumentException if {@code duration} is negative
 * @throws IllegalStateException if the time to live or time to idle was already set
 */
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
  checkState(
      expireAfterWriteNanos == UNSET_INT,
      "expireAfterWrite was already set to %s ns",
      expireAfterWriteNanos);
  checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
  this.expireAfterWriteNanos = unit.toNanos(duration);
  return this;
}