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

The following examples show how to use java.util.concurrent.TimeUnit#toNanos() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LinkedBlockingDeque.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public E pollFirst(long timeout, TimeUnit unit)
    throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        E x;
        while ( (x = unlinkFirst()) == null) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        return x;
    } finally {
        lock.unlock();
    }
}
 
Example 2
Source File: Uninterruptibles.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Invokes {@code semaphore.}{@link Semaphore#tryAcquire(int, long, TimeUnit) tryAcquire(permits,
 * timeout, unit)} uninterruptibly.
 *
 * @since 18.0
 */

@GwtIncompatible // concurrency
public static boolean tryAcquireUninterruptibly(Semaphore semaphore, int permits, long timeout, TimeUnit unit) {
  boolean interrupted = false;
  try {
    long remainingNanos = unit.toNanos(timeout);
    long end = System.nanoTime() + remainingNanos;
    while (true) {
      try {
        // Semaphore treats negative timeouts just like zero.
        return semaphore.tryAcquire(permits, remainingNanos, NANOSECONDS);
      } catch (InterruptedException e) {
        interrupted = true;
        remainingNanos = end - System.nanoTime();
      }
    }
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 3
Source File: StampedLock.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 tryWriteLock(long time, TimeUnit unit)
    throws InterruptedException {
    long nanos = unit.toNanos(time);
    if (!Thread.interrupted()) {
        long next, deadline;
        if ((next = tryWriteLock()) != 0L)
            return next;
        if (nanos <= 0L)
            return 0L;
        if ((deadline = System.nanoTime() + nanos) == 0L)
            deadline = 1L;
        if ((next = acquireWrite(true, deadline)) != INTERRUPTED)
            return next;
    }
    throw new InterruptedException();
}
 
Example 4
Source File: StampedLock.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 tryWriteLock(long time, TimeUnit unit)
    throws InterruptedException {
    long nanos = unit.toNanos(time);
    if (!Thread.interrupted()) {
        long next, deadline;
        if ((next = tryWriteLock()) != 0L)
            return next;
        if (nanos <= 0L)
            return 0L;
        if ((deadline = System.nanoTime() + nanos) == 0L)
            deadline = 1L;
        if ((next = acquireWrite(true, deadline)) != INTERRUPTED)
            return next;
    }
    throw new InterruptedException();
}
 
Example 5
Source File: FileTime.java    From jdk-1.7-annotated with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes a new instance of this class.
 */
DaysAndNanos(long value, TimeUnit unit) {
    long scale;
    switch (unit) {
        case DAYS         : scale = C0; break;
        case HOURS        : scale = C1; break;
        case MINUTES      : scale = C2; break;
        case SECONDS      : scale = C3; break;
        case MILLISECONDS : scale = C4; break;
        case MICROSECONDS : scale = C5; break;
        case NANOSECONDS  : scale = C6; break;
        default : throw new AssertionError("Unit not handled");
    }
    this.days = unit.toDays(value);
    this.excessNanos = unit.toNanos(value - (this.days * scale));
}
 
Example 6
Source File: StampedLock.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 tryWriteLock(long time, TimeUnit unit)
    throws InterruptedException {
    long nanos = unit.toNanos(time);
    if (!Thread.interrupted()) {
        long next, deadline;
        if ((next = tryWriteLock()) != 0L)
            return next;
        if (nanos <= 0L)
            return 0L;
        if ((deadline = System.nanoTime() + nanos) == 0L)
            deadline = 1L;
        if ((next = acquireWrite(true, deadline)) != INTERRUPTED)
            return next;
    }
    throw new InterruptedException();
}
 
Example 7
Source File: AbstractQueuedSynchronizer.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements timed condition wait.
 * <ol>
 * <li> If current thread is interrupted, throw InterruptedException.
 * <li> Save lock state returned by {@link #getState}.
 * <li> Invoke {@link #release} with saved state as argument,
 *      throwing IllegalMonitorStateException if it fails.
 * <li> Block until signalled, interrupted, or timed out.
 * <li> Reacquire by invoking specialized version of
 *      {@link #acquire} with saved state as argument.
 * <li> If interrupted while blocked in step 4, throw InterruptedException.
 * <li> If timed out while blocked in step 4, return false, else true.
 * </ol>
 */
public final boolean await(long time, TimeUnit unit)
        throws InterruptedException {
    long nanosTimeout = unit.toNanos(time);
    if (Thread.interrupted())
        throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    final long deadline = System.nanoTime() + nanosTimeout;
    boolean timedout = false;
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
        if (nanosTimeout <= 0L) {
            timedout = transferAfterCancelledWait(node);
            break;
        }
        if (nanosTimeout >= spinForTimeoutThreshold)
            LockSupport.parkNanos(this, nanosTimeout);
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
            break;
        nanosTimeout = deadline - System.nanoTime();
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
        unlinkCancelledWaiters();
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
    return !timedout;
}
 
Example 8
Source File: ServerImpl.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
  synchronized (lock) {
    long timeoutNanos = unit.toNanos(timeout);
    long endTimeNanos = System.nanoTime() + timeoutNanos;
    while (!terminated && (timeoutNanos = endTimeNanos - System.nanoTime()) > 0) {
      NANOSECONDS.timedWait(lock, timeoutNanos);
    }
    return terminated;
  }
}
 
Example 9
Source File: AbstractQueuedLongSynchronizer.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implements timed condition wait.
 * <ol>
 * <li> If current thread is interrupted, throw InterruptedException.
 * <li> Save lock state returned by {@link #getState}.
 * <li> Invoke {@link #release} with saved state as argument,
 *      throwing IllegalMonitorStateException if it fails.
 * <li> Block until signalled, interrupted, or timed out.
 * <li> Reacquire by invoking specialized version of
 *      {@link #acquire} with saved state as argument.
 * <li> If interrupted while blocked in step 4, throw InterruptedException.
 * <li> If timed out while blocked in step 4, return false, else true.
 * </ol>
 */
public final boolean await(long time, TimeUnit unit)
        throws InterruptedException {
    long nanosTimeout = unit.toNanos(time);
    if (Thread.interrupted())
        throw new InterruptedException();
    Node node = addConditionWaiter();
    long savedState = fullyRelease(node);
    final long deadline = System.nanoTime() + nanosTimeout;
    boolean timedout = false;
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
        if (nanosTimeout <= 0L) {
            timedout = transferAfterCancelledWait(node);
            break;
        }
        if (nanosTimeout >= spinForTimeoutThreshold)
            LockSupport.parkNanos(this, nanosTimeout);
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
            break;
        nanosTimeout = deadline - System.nanoTime();
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
        unlinkCancelledWaiters();
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
    return !timedout;
}
 
Example 10
Source File: AbstractQueuedLongSynchronizer.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Implements timed condition wait.
 * <ol>
 * <li> If current thread is interrupted, throw InterruptedException.
 * <li> Save lock state returned by {@link #getState}.
 * <li> Invoke {@link #release} with saved state as argument,
 *      throwing IllegalMonitorStateException if it fails.
 * <li> Block until signalled, interrupted, or timed out.
 * <li> Reacquire by invoking specialized version of
 *      {@link #acquire} with saved state as argument.
 * <li> If interrupted while blocked in step 4, throw InterruptedException.
 * <li> If timed out while blocked in step 4, return false, else true.
 * </ol>
 */
public final boolean await(long time, TimeUnit unit)
        throws InterruptedException {
    long nanosTimeout = unit.toNanos(time);
    if (Thread.interrupted())
        throw new InterruptedException();
    Node node = addConditionWaiter();
    long savedState = fullyRelease(node);
    final long deadline = System.nanoTime() + nanosTimeout;
    boolean timedout = false;
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
        if (nanosTimeout <= 0L) {
            timedout = transferAfterCancelledWait(node);
            break;
        }
        if (nanosTimeout >= spinForTimeoutThreshold)
            LockSupport.parkNanos(this, nanosTimeout);
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
            break;
        nanosTimeout = deadline - System.nanoTime();
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null)
        unlinkCancelledWaiters();
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
    return !timedout;
}
 
Example 11
Source File: SortedKafkaMessageBuffer.java    From extension-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();

    try {
        while (this.count == 0) {
            if (nanos <= 0) {
                return null;
            }
            nanos = this.notEmpty.awaitNanos(nanos);
        }

        E removed = remove();
        if (logger.isDebugEnabled()) {
            logger.debug("Buffer state after removing element [{}]", removed);
            for (E message : delegate) {
                logger.debug(
                        "Partition:{}, Offset:{}, Timestamp:{}, Payload:{}",
                        message.partition(), message.offset(), message.value(), message.timestamp()
                );
            }
        }
        return removed;
    } finally {
        lock.unlock();
    }
}
 
Example 12
Source File: BusySpinWaitConditionStrategy.java    From util4j with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T waitFor(WaitCondition<T> waitCondition, long timeOut, TimeUnit unit) throws InterruptedException {
	long endTime=System.nanoTime()+unit.toNanos(timeOut);
   	while(!waitCondition.isComplete())
	{
   		if(System.nanoTime()>=endTime)
   		{
   			break;
   		}
	}
	return waitCondition.getAttach();
}
 
Example 13
Source File: ActorSystemScheduledExecutorAdapter.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public ScheduledFuture<?> schedule(@Nonnull Runnable command, long delay, @Nonnull TimeUnit unit) {
	ScheduledFutureTask<Void> scheduledFutureTask = new ScheduledFutureTask<>(command, unit.toNanos(delay), 0L);

	Cancellable cancellable = internalSchedule(scheduledFutureTask, delay, unit);

	scheduledFutureTask.setCancellable(cancellable);

	return scheduledFutureTask;
}
 
Example 14
Source File: SummedBlockingQueue.java    From ddal with Apache License 2.0 5 votes vote down vote up
private long recursiveGetFromQueue(long timeout, TimeUnit unit) throws TimeoutException, InterruptedException {
    long nanoTimeout = unit.toNanos(timeout);
    while (true) {
        long now = System.nanoTime();
        InnerSequenceRange sequenceRange = get(nanoTimeout);
        if (sequenceRange == null) {
            throw new TimeoutException(timeout + " " + unit);
        } else {
            long id = sequenceRange.getCounter().getAndIncrement();
            if (id <= sequenceRange.getEndValue()) {
                long c = countForSum.decrementAndGet();
                if (c == sum - 1) {
                    signalNotFull();
                }
                if (id == sequenceRange.getEndValue()) {
                    remove(sequenceRange);
                } else {
                    threadLocal.set(sequenceRange);
                }
                return id;
            } else {
                remove(sequenceRange);
                nanoTimeout -= System.nanoTime() - now;
                if (nanoTimeout <= 0) {
                    throw new TimeoutException(timeout + " " + unit);
                }
            }
        }
    }
}
 
Example 15
Source File: DeadlineTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
public void increment(long period, TimeUnit unit) {
  if (period < 0) {
    throw new IllegalArgumentException();
  }
  this.time += unit.toNanos(period);
}
 
Example 16
Source File: QueueWorkerThreadPoolExecutor.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial parameters.
 *
 * @param corePoolSize
 *            the number of threads to keep in the pool, even if they are idle, unless
 *            {@code allowCoreThreadTimeOut} is set
 * @param maximumPoolSize
 *            the maximum number of threads to allow in the pool
 * @param keepAliveTime
 *            when the number of threads is greater than the core, this is the maximum time that excess idle threads
 *            will wait for new tasks before terminating.
 * @param unit
 *            the time unit for the {@code keepAliveTime} argument
 * @param workQueue
 *            the queue to use for holding tasks before they are executed. This queue will hold only the
 *            {@code Runnable} tasks submitted by the {@code execute} method.
 * @param threadFactory
 *            the factory to use when the executor creates a new thread
 * @param handler
 *            the handler to use when execution is blocked because the thread bounds and queue capacities are
 *            reached
 * @throws IllegalArgumentException
 *             if one of the following holds:<br>
 *             {@code corePoolSize < 0}<br>
 *             {@code keepAliveTime < 0}<br>
 *             {@code maximumPoolSize <= 0}<br>
 *             {@code maximumPoolSize < corePoolSize}
 * @throws NullPointerException
 *             if {@code workQueue} or {@code threadFactory} or {@code handler} is null
 */
public QueueWorkerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
        QueueWorkerRejectedExecutionHandler handler) {

    if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}
 
Example 17
Source File: Phaser.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 18
Source File: DefaultStatisticsCalculator.java    From junitperf with Apache License 2.0 4 votes vote down vote up
@Override
public float getMeanLatency(TimeUnit unit) {
    return (float) latencyStatistics.getMean() / unit.toNanos(1);
}
 
Example 19
Source File: CacheBuilder.java    From bazel-buildfarm with Apache License 2.0 3 votes vote down vote up
/**
 * Specifies that active entries are eligible for automatic refresh once a fixed duration has
 * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
 * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
 * CacheLoader#reload}.
 *
 * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
 * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
 * implementation; otherwise refreshes will be performed during unrelated cache read and write
 * operations.
 *
 * <p>Currently automatic refreshes are performed when the first stale request for an entry
 * occurs. The request triggering refresh will make a blocking call to {@link CacheLoader#reload}
 * and immediately return the new value if the returned future is complete, and the old value
 * otherwise.
 *
 * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
 *
 * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
 * when feasible), use {@link #refreshAfterWrite(Duration)} instead.
 *
 * @param duration the length of time after an entry is created that it should be considered
 *     stale, and thus eligible for refresh
 * @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 refresh interval was already set
 * @since 11.0
 */
@GwtIncompatible // To be supported (synchronously).
public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
  checkNotNull(unit);
  checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
  checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
  this.refreshNanos = unit.toNanos(duration);
  return this;
}
 
Example 20
Source File: GrpcCleanupRule.java    From grpc-java with Apache License 2.0 2 votes vote down vote up
/**
 * Sets a positive total time limit for the automatic resource cleanup. If any of the resources
 * registered to the rule fails to be released in time, the test will fail.
 *
 * <p>Note that the resource cleanup duration may or may not be counted as part of the JUnit
 * {@link org.junit.rules.Timeout Timeout} rule's test duration, depending on which rule is
 * applied first.
 *
 * @return this
 */
public GrpcCleanupRule setTimeout(long timeout, TimeUnit timeUnit) {
  checkArgument(timeout > 0, "timeout should be positive");
  timeoutNanos = timeUnit.toNanos(timeout);
  return this;
}