Example usage for java.util.concurrent TimeUnit toNanos

List of usage examples for java.util.concurrent TimeUnit toNanos

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit toNanos.

Prototype

public long toNanos(long duration) 

Source Link

Document

Equivalent to #convert(long,TimeUnit) NANOSECONDS.convert(duration, this) .

Usage

From source file:com.cloudbees.hudson.plugins.folder.computed.EventOutputStreams.java

public EventOutputStreams(OutputFile outputFile, long flushInterval, TimeUnit flushIntervalUnits, int flushSize,
        boolean append, long rotateSize, int fileCount) {
    this.outputFile = outputFile;
    this.flushIntervalNanos = flushIntervalUnits.toNanos(flushInterval);
    this.flushSize = flushSize;
    this.fileCount = fileCount;
    this.rotateSize = rotateSize;
    this.appendNextOpen = append;
    this.lastFlushNanos = System.nanoTime();
}

From source file:meme.singularsyntax.concurrency.ContinuableFutureTask.java

/**
 * @throws CancellationException {@inheritDoc}
 *///from  w  ww  . j av  a  2  s .c  om
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    return sync.innerGet(unit.toNanos(timeout));
}

From source file:io.netty.handler.timeout.IdleStateHandler.java

/**
 * Creates a new instance firing {@link IdleStateEvent}s.
 *
 * @param readerIdleTime/*  www . j av a2  s .c o  m*/
 *        an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}
 *        will be triggered when no read was performed for the specified
 *        period of time.  Specify {@code 0} to disable.
 * @param writerIdleTime
 *        an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}
 *        will be triggered when no write was performed for the specified
 *        period of time.  Specify {@code 0} to disable.
 * @param allIdleTime
 *        an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}
 *        will be triggered when neither read nor write was performed for
 *        the specified period of time.  Specify {@code 0} to disable.
 * @param unit
 *        the {@link TimeUnit} of {@code readerIdleTime},
 *        {@code writeIdleTime}, and {@code allIdleTime}
 */
public IdleStateHandler(long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) {
    if (unit == null) {
        throw new NullPointerException("unit");
    }

    if (readerIdleTime <= 0) {
        readerIdleTimeNanos = 0;
    } else {
        readerIdleTimeNanos = Math.max(unit.toNanos(readerIdleTime), MIN_TIMEOUT_NANOS);
    }
    if (writerIdleTime <= 0) {
        writerIdleTimeNanos = 0;
    } else {
        writerIdleTimeNanos = Math.max(unit.toNanos(writerIdleTime), MIN_TIMEOUT_NANOS);
    }
    if (allIdleTime <= 0) {
        allIdleTimeNanos = 0;
    } else {
        allIdleTimeNanos = Math.max(unit.toNanos(allIdleTime), MIN_TIMEOUT_NANOS);
    }
}

From source file:LinkedTransferQueue.java

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    Object e = xfer(null, TIMEOUT, unit.toNanos(timeout));
    if (e != null || !Thread.interrupted()) {
        return cast(e);
    }//from  w ww.  jav a2  s  . c om
    throw new InterruptedException();
}

From source file:com.addthis.hydra.task.source.AbstractStreamFileDataSource.java

private Bundle pollAndCloseOnInterrupt(long pollFor, TimeUnit unit) {
    boolean interrupted = false;
    try {/* w  w  w. jav  a2 s . c o  m*/
        long remainingNanos = unit.toNanos(pollFor);
        long end = System.nanoTime() + remainingNanos;
        while (true) {
            try {
                return queue.poll(remainingNanos, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                interrupted = true;
                log.info("interrupted while polling for bundles; closing source then resuming poll");
                close();
                remainingNanos = end - System.nanoTime();
            }
        }
    } finally {
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

/**
 * 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./*from w ww  .  j  a v a 2  s  .c  om*/
 *
 * @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();
    long t = now();
    TenantQueue.Item item = null;
    try {
        for (;;) {
            TenantQueue q = nextQueue(t);
            if (q == null) {
                if (nanos <= 0)
                    return null;
                else
                    nanos = available.awaitNanos(nanos);
            } else {
                long delay = q.next - t;
                if (delay <= 0) {
                    item = q.poll(t);
                    return item == null ? null : item.element;
                }
                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;
                    }
                }
            }
            t = System.nanoTime();
        }
    } finally {
        if (leader == null && hasNext())
            available.signal();
        lock.unlock();
        done(item, t);
    }
}

From source file:metlos.executors.batch.BatchExecutor.java

/**
 * Another variation on {@link #invokeAllWithin(Collection, long, TimeUnit)}. The commands
 * will be run repeatedly (forever) with each "batch" executing with given duration.
 * There will be a given delay between two consecutive executions of the command sets.
 * <p>//from ww w .j  ava2 s.  co  m
 * Each execution takes a snapshot of the provided collection and executes only the commands
 * present in the collection at the time of the call of this method. Once all the commands executed,
 * another snapshot of the collection is taken and the commands are rescheduled.
 * <p>
 * This means that if you intend the collection of the commands to be mutable and change over time once
 * it has been submitted to the executor, the collection <b>MUST</b> be able to handle concurrent
 * access and modification.
 * 
 * @param commands the collection of commands to repeatedly execute
 * @param initialDelay the initial delay before the execution starts (in the provided time unit)
 * @param duration the expected duration of the execution of all commands
 * @param delay the delay between two consecutive executions of the command sets
 * @param unit the time unit of the time related parameters
 */
public void submitWithPreferedDurationAndFixedDelay(Collection<? extends Runnable> commands, long initialDelay,
        long duration, long delay, TimeUnit unit) {
    prepareForNextRepetition(commands);

    BatchRecord batchRecord = createNewBatchRecord(commands.size(), unit, duration, initialDelay);

    RepetitionRecord repetitionRecord = new RepetitionRecord();
    repetitionRecord.tasks = commands;
    repetitionRecord.delayNanos = unit.toNanos(delay);
    repetitionRecord.durationNanos = unit.toNanos(duration);

    long idealFinishTime = batchRecord.nextElementStartTime.get();
    long increment = (batchRecord.finishTimeNanos - idealFinishTime) / batchRecord.nofElements;
    for (Runnable command : commands) {
        RunnableFuture<?> task = newTaskFor(command, null, batchRecord, repetitionRecord, idealFinishTime);
        super.execute(task);
        idealFinishTime += increment;
    }
}

From source file:LinkedTransferQueue.java

public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException {
    if (e == null) {
        throw new NullPointerException();
    }/*from w  w  w.ja  va2  s .com*/
    if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null) {
        return true;
    }
    if (!Thread.interrupted()) {
        return false;
    }
    throw new InterruptedException();
}

From source file:com.ryantenney.metrics.spring.reporter.AbstractScheduledReporterFactoryBean.java

/**
 * Parses and converts to nanoseconds a string representing
 * a duration, ie: 500ms, 30s, 5m, 1h, etc
 * @param duration a string representing a duration
 * @return the duration in nanoseconds//from   w ww .j  a v a 2  s.c om
 */
protected long convertDurationString(String duration) {
    final Matcher m = DURATION_STRING_PATTERN.matcher(duration);
    if (!m.matches()) {
        throw new IllegalArgumentException("Invalid duration string format");
    }

    final long sourceDuration = Long.parseLong(m.group(1));
    final String sourceUnitString = m.group(2);
    final TimeUnit sourceUnit;
    if ("ns".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.NANOSECONDS;
    } else if ("us".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MICROSECONDS;
    } else if ("ms".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MILLISECONDS;
    } else if ("s".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.SECONDS;
    } else if ("m".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.MINUTES;
    } else if ("h".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.HOURS;
    } else if ("d".equalsIgnoreCase(sourceUnitString)) {
        sourceUnit = TimeUnit.DAYS;
    } else {
        sourceUnit = TimeUnit.MILLISECONDS;
    }

    return sourceUnit.toNanos(sourceDuration);
}

From source file:LinkedTransferQueue.java

/**
 * Transfers the element to a consumer if it is possible to do so
 * before the timeout elapses.//from  ww w  .  j av a  2s. co m
 *
 * <p>More precisely, transfers the specified element immediately
 * if there exists a consumer already waiting to receive it (in
 * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
 * else inserts the specified element at the tail of this queue
 * and waits until the element is received by a consumer,
 * returning {@code false} if the specified wait time elapses
 * before the element can be transferred.
 *
 * @throws NullPointerException if the specified element is null
 */
public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException {
    if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
        return true;
    if (!Thread.interrupted())
        return false;
    throw new InterruptedException();
}