Java Code Examples for java.util.concurrent.TimeUnit

The following are top voted examples for showing how to use java.util.concurrent.TimeUnit. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: strongback-java   File: Strongback.java View source code 7 votes vote down vote up
private LongConsumer monitorDelay(long executionInterval, TimeUnit unit) {
    long intervalInMs = unit.toMillis(executionInterval);
    return delayInMs -> {
        if (delayInMs > intervalInMs) {
            executorDelayCounter.incrementAndGet();
            if (excessiveExecutionHandler != null) {
                try {
                    excessiveExecutionHandler.accept(delayInMs);
                } catch (Throwable t) {
                    logger().error(t, "Error with custom handler for excessive execution times");
                }
            } else {
                logger().error("Unable to execute all activities within " + intervalInMs + " milliseconds!");
            }
        }
    };
}
 
Example 2
Project: exploratorium-android-rest   File: FutureResult.java View source code 7 votes vote down vote up
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    synchronized (this) {
        if (!done) {
            unit.timedWait(this, timeout);
        }
    }

    if (throwable != null) {
        throw new ExecutionException(throwable);
    }

    return result;
}
 
Example 3
Project: Time4J   File: PrettyTime.java View source code 7 votes vote down vote up
/**
 * <p>Formats given time point relative to the current time of [email protected] #getReferenceClock()}
 * as duration in given precision or as absolute date-time. </p>
 *
 * @param   moment      relative time point
 * @param   tz          time zone for translating to a local duration
 * @param   precision   maximum precision of relative time (not more than seconds)
 * @param   maxdelta    maximum deviation of given moment from clock in posix seconds for relative printing
 * @param   formatter   used for printing absolute time if the deviation is bigger than maxdelta
 * @return  formatted output of relative time, either in past or in future
 * @since   3.6/4.4
 */
/*[deutsch]
 * <p>Formatiert den angegebenen Zeitpunkt relativ zur aktuellen Zeit
 * der Referenzuhr [email protected] #getReferenceClock()} als Dauer in der angegebenen
 * maximalen Genauigkeit oder als absolute Datumszeit. </p>
 *
 * @param   moment      relative time point
 * @param   tz          time zone for translating to a local duration
 * @param   precision   maximum precision of relative time (not more than seconds)
 * @param   maxdelta    maximum deviation of given moment from clock in posix seconds for relative printing
 * @param   formatter   used for printing absolute time if the deviation is bigger than maxdelta
 * @return  formatted output of relative time, either in past or in future
 * @since   3.6/4.4
 */
public String printRelativeOrDateTime(
    UnixTime moment,
    Timezone tz,
    TimeUnit precision,
    long maxdelta,
    TemporalFormatter<Moment> formatter
) {

    UnixTime ref = this.getReferenceClock().currentTime();
    Moment t1 = Moment.from(ref);
    Moment t2 = Moment.from(moment);
    long delta = t1.until(t2, TimeUnit.SECONDS);

    if (Math.abs(delta) > maxdelta) {
        return formatter.format(t2);
    } else if (
        (precision.compareTo(TimeUnit.SECONDS) <= 0)
        && (Math.abs(delta) < 60L)
    ) {
        return this.printRelativeSeconds(t1, t2, delta);
    }

    return this.printRelativeTime(t1, t2, tz, precision, null, null);

}
 
Example 4
Project: vibe   File: Triggers.java View source code 7 votes vote down vote up
private static String toReadable(TimeUnit unit, long duration)
{
	boolean one = duration == 1;
	
	switch(unit)
	{
		case DAYS:
			return one ? "day" : "days";
		case HOURS:
			return one ? "hour" : "hours";
		case MICROSECONDS:
			return one ? "microsecond" : "microseconds";
		case MILLISECONDS:
			return one ? "millisecond" : "milliseconds";
		case MINUTES:
			return one ? "minute" : "minutes";
		case NANOSECONDS:
			return one ? "nanosecond" : "nanoseconds";
		case SECONDS:
			return one ? "second" : "seconds";
	}
	
	return unit.toString();
}
 
Example 5
Project: android-platform-tools-base   File: HandleProfiling.java View source code 7 votes vote down vote up
/**
 * Send a SPSS (Sampling Profiling Streaming Start) request to the client.
 *
 * @param bufferSize is the desired buffer size in bytes (8MB is good)
 * @param samplingInterval sampling interval
 * @param samplingIntervalTimeUnits units for sampling interval
 */
public static void sendSPSS(Client client, int bufferSize, int samplingInterval,
        TimeUnit samplingIntervalTimeUnits) throws IOException {
    int interval = (int) samplingIntervalTimeUnits.toMicros(samplingInterval);

    ByteBuffer rawBuf = allocBuffer(3*4);
    JdwpPacket packet = new JdwpPacket(rawBuf);
    ByteBuffer buf = getChunkDataBuf(rawBuf);

    buf.putInt(bufferSize);
    buf.putInt(0); // flags
    buf.putInt(interval);

    finishChunkPacket(packet, CHUNK_SPSS, buf.position());
    Log.d("ddm-prof", "Sending " + name(CHUNK_SPSS)
            + "', size=" + bufferSize + ", flags=0, samplingInterval=" + interval);
    client.sendAndConsume(packet, mInst);

    // send a status query. this ensure that the status is properly updated if for some
    // reason starting the tracing failed.
    sendMPRQ(client);
}
 
Example 6
Project: urmia   File: FileTime.java View source code 7 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 7
Project: lettuce   File: DefaultEventPublisherOptionsTest.java View source code 6 votes vote down vote up
@Test
public void testDisabled() throws Exception {

    DefaultEventPublisherOptions sut = DefaultEventPublisherOptions.disabled();

    assertThat(sut.eventEmitInterval()).isEqualTo(0);
    assertThat(sut.eventEmitIntervalUnit()).isEqualTo(TimeUnit.SECONDS);
}
 
Example 8
Project: lettuce   File: PoolConnectionTest.java View source code 6 votes vote down vote up
@Test
public void syncPoolPerformanceTest() throws Exception {

    RedisConnectionPool<RedisConnection<String, String>> pool = client.pool();
    RedisConnection<String, String> c1 = pool.allocateConnection();

    c1.ping();
    Stopwatch stopwatch = Stopwatch.createStarted();

    for (int i = 0; i < 1000; i++) {
        c1.ping();
    }

    long elapsed = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);

    log.info("syncPoolPerformanceTest Duration: " + elapsed + "ms");

}
 
Example 9
Project: strongback-java   File: Strongback.java View source code 6 votes vote down vote up
/**
 * Use the specified execution rate for Strongback's [email protected] Strongback#executor() executor}. The default execution rate
 * is 5 milliseconds.
 * <p>
 * The clock that Strongback is configured to use will also affect the precision of the execution rate: the
 * [email protected] #useFpgaTime() FPGA clock} will likely support rates down to around a few milliseconds, whereas the
 * [email protected] #useSystemTime() system clock} may only support rates of 10-15 milliseconds. Therefore, this method does not
 * currently allow sub-microsecond intervals.
 *
 * @param interval the interval for calling all registered [email protected] Executable}s; must be positive
 * @param unit the time unit for the interval; may not be null
 * @return this configurator so that methods can be chained together; never null
 * @see #useExecutionTimerMode(TimerMode)
 * @throws IllegalArgumentException if [email protected] unit} is [email protected] TimeUnit#MICROSECONDS} or [email protected] TimeUnit#NANOSECONDS}
 */
public Configurator useExecutionPeriod(long interval, TimeUnit unit) {
    if (interval <= 0) throw new IllegalArgumentException("The execution interval must be positive");
    if (unit == null) throw new IllegalArgumentException("The time unit may not be null");
    if (TimeUnit.MILLISECONDS.toNanos(1) > unit.toNanos(interval)) {
        throw new IllegalArgumentException("The interval must be at least 1 millisecond");
    }
    executionPeriodInNanos = unit.toNanos(interval);
    return this;
}
 
Example 10
Project: lettuce   File: DefaultCommandLatencyCollector.java View source code 6 votes vote down vote up
private CommandLatency getMetric(Histogram histogram) {
    Map<Double, Long> percentiles = getPercentiles(histogram);

    TimeUnit timeUnit = options.targetUnit();
    CommandLatency metric = new CommandLatency(timeUnit.convert(histogram.getMinValue(), TimeUnit.NANOSECONDS),
            timeUnit.convert(histogram.getMaxValue(), TimeUnit.NANOSECONDS), percentiles);

    return metric;
}
 
Example 11
Project: lettuce   File: DefaultEventPublisherOptionsTest.java View source code 6 votes vote down vote up
@Test
public void testDefault() throws Exception {

    DefaultEventPublisherOptions sut = DefaultEventPublisherOptions.create();

    assertThat(sut.eventEmitInterval()).isEqualTo(10);
    assertThat(sut.eventEmitIntervalUnit()).isEqualTo(TimeUnit.MINUTES);
}
 
Example 12
Project: strongback-java   File: Metronome.java View source code 6 votes vote down vote up
/**
 * Create a new metronome that starts ticking immediately and that uses [email protected] LockSupport#parkNanos(long)} to wait.
 * <p>
 * [email protected] LockSupport#parkNanos(long)} uses the underlying platform-specific timed wait mechanism, which may be more
 * accurate for smaller periods than [email protected] #sleeper(long, TimeUnit, Clock)}. However, like
 * [email protected] #sleeper(long, TimeUnit, Clock)}, the resulting Metronome may result in (expensive) thread context switches.
 * <p>
 * Although the method seemingly supports taking [email protected] TimeUnit#MICROSECONDS} and [email protected] TimeUnit#NANOSECONDS}, it is
 * likely that the JVM and operating system do not support such fine-grained precision. And as mentioned above, care should
 * be used when specifying a [email protected] period} of 10-15 milliseconds or smaller.
 *
 * @param period the period of time that the metronome ticks and for which [email protected] #pause()} waits
 * @param unit the unit of time; may not be null
 * @param timeSystem the time system that will provide the current time; may not be null
 * @return the new metronome; never null
 */
public static Metronome parker(long period, TimeUnit unit, Clock timeSystem) {
    long periodInNanos = unit.toNanos(period);
    return new Metronome() {
        private long next = timeSystem.currentTimeInNanos() + periodInNanos;

        @Override
        public boolean pause() {
            while (next > timeSystem.currentTimeInNanos()) {
                LockSupport.parkNanos(next - timeSystem.currentTimeInNanos());
            }
            next = next + periodInNanos;
            return true;
        }

        @Override
        public String toString() {
            return "Metronome (park for " + TimeUnit.NANOSECONDS.toMillis(periodInNanos) + " ms)";
        }
    };
}
 
Example 13
Project: lettuce   File: RedisURIBuilderTest.java View source code 6 votes vote down vote up
@Test
public void sentinel() throws Exception {
    RedisURI result = RedisURI.Builder.sentinel("localhost").withTimeout(2, TimeUnit.HOURS).build();
    assertThat(result.getSentinels()).hasSize(1);
    assertThat(result.getTimeout()).isEqualTo(2);
    assertThat(result.getUnit()).isEqualTo(TimeUnit.HOURS);
}
 
Example 14
Project: lettuce   File: DefaultDefaultCommandLatencyCollectorOptionsTest.java View source code 6 votes vote down vote up
@Test
public void testDefault() throws Exception {

    DefaultCommandLatencyCollectorOptions sut = DefaultCommandLatencyCollectorOptions.create();

    assertThat(sut.targetPercentiles()).hasSize(5);
    assertThat(sut.targetUnit()).isEqualTo(TimeUnit.MICROSECONDS);
}
 
Example 15
Project: java-string-algorithms   File: BoyerMooreTest.java View source code 6 votes vote down vote up
@Test
@Ignore
public void benchmark() throws Exception {
  File beowulf = new File(getClass().getClassLoader().getResource("anonymous-beowulf-543.txt").getFile());
  final String beowulfText = Files.toString(beowulf, Charsets.UTF_8);
  final String search = "Beowulf finally accepted Hygd's offer of kingdom and hoard";
  final StringFinder stringFinder = searchApi().compileFinder(search);
  TestHelp.Callback<Integer> callback = new TestHelp.Callback<java.lang.Integer>() {
    int garbage;

    @Override
    public void consume(Integer value) {
      garbage |= value;
    }
  };
  Callable<Integer> stringIndexOf = new Callable<Integer>() {
    @SuppressWarnings({"RedundantStringConstructorCall"})
    @Override
    public Integer call() throws Exception {
      return new String(beowulfText).indexOf(search);
    }
  };
  Callable<Integer> boyerMoore = new Callable<Integer>() {
    @SuppressWarnings({"RedundantStringConstructorCall"})
    @Override
    public Integer call() throws Exception {
      return stringFinder.indexIn(new String(beowulfText));
    }
  };
  timeMultipleCalls(stringIndexOf, 100, callback, TimeUnit.DAYS);
  timeMultipleCalls(boyerMoore, 100, callback, TimeUnit.DAYS);
  System.gc();
  Thread.sleep(500L);
  System.gc();
  for (int i = 0; i < 10; i++) {
    timeAndLogMultipleCalls("String.indexOf", stringIndexOf, 10000, callback, TimeUnit.MILLISECONDS);
    timeAndLogMultipleCalls("  Boyter-Moore", boyerMoore, 10000, callback, TimeUnit.MILLISECONDS);
  }
}
 
Example 16
Project: images3-play   File: ImagePlantController.java View source code 6 votes vote down vote up
public Result getImageReport(String id, String templateName, Long startTime,
        Long length, String timeUnit, String types) throws JsonProcessingException {
    if (null != templateName 
            && templateName.trim().length() == 0) {
        templateName = null;
    }
    TimeInterval interval = 
            new TimeInterval(new Date(startTime), length, TimeUnit.valueOf(timeUnit));
    ImageReportQueryRequest request = 
            new ImageReportQueryRequest(
                    id, templateName, interval, getImageReportTypes(types));
    ImageReportResponse response = imageS3.getImageReport(request);
    String respJson = objectMapper.writeValueAsString(response);
    return ok(respJson);
}
 
Example 17
Project: android-platform-tools-base   File: TimeUtils.java View source code 6 votes vote down vote up
public static String makeHumanReadable(long time, long span, TimeUnit timeUnits) {
    String units;
    double scale;
    if (timeUnits.toSeconds(span) > 0) {
        units = "s";
        scale = 1e-9;
    } else if (timeUnits.toMillis(span) > 0) {
        units = "ms";
        scale = 1e-6;
    } else {
        units = "us";
        scale = 1e-3;
    }

    return String.format("%1$s %2$s", formatTime(timeUnits.toNanos(time), scale), units);
}
 
Example 18
Project: airlift   File: Duration.java View source code 6 votes vote down vote up
public Duration convertToMostSuccinctTimeUnit()
{
    TimeUnit unitToUse = NANOSECONDS;
    for (TimeUnit unitToTest : TimeUnit.values()) {
        // since time units are powers of ten, we can get rounding errors here, so fuzzy match
        if (getValue(unitToTest) > 0.9999) {
            unitToUse = unitToTest;
        }
        else {
            break;
        }
    }
    return convertTo(unitToUse);
}
 
Example 19
Project: s1   File: BasicTest.java View source code 6 votes vote down vote up
protected void sleep(long time, TimeUnit tu){
    try {
        tu.sleep(time);
    } catch (InterruptedException e) {
        wrap(e);
    }
}
 
Example 20
Project: Time4J   File: PrettyTime.java View source code 6 votes vote down vote up
private String printRelativeTime(
    Moment ref,
    Moment moment,
    Timezone tz,
    TimeUnit precision,
    CalendarUnit maxRelativeUnit,
    TemporalFormatter<Moment> formatter
) {

    PlainTimestamp start =
        PlainTimestamp.from(
            ref,
            tz.getOffset(ref));
    PlainTimestamp end =
        PlainTimestamp.from(
            moment,
            tz.getOffset(moment));

    IsoUnit[] units = (this.weekToDays ? TSP_UNITS : STD_UNITS);
    Duration<IsoUnit> duration = Duration.in(tz, units).between(start, end);

    if (duration.isEmpty()) {
        return this.getEmptyRelativeString(precision);
    }

    TimeSpan.Item<IsoUnit> item = duration.getTotalLength().get(0);
    long amount = item.getAmount();
    IsoUnit unit = item.getUnit();

    if (unit instanceof ClockUnit) {
        if (5 - ((ClockUnit) unit).ordinal() < precision.ordinal()) {
            return this.getEmptyRelativeString(precision);
        }
    } else if (
        (maxRelativeUnit != null)
        && (Double.compare(unit.getLength(), maxRelativeUnit.getLength()) > 0)
    ) {
        return formatter.format(moment);
    } else if (
        (amount == 1L)
        && unit.equals(CalendarUnit.DAYS)
    ) {
        UnitPatterns patterns = UnitPatterns.of(this.locale);
        String replacement = (duration.isNegative() ? patterns.getYesterdayWord() : patterns.getTomorrowWord());

        if (!replacement.isEmpty()) {
            return replacement;
        }
    }

    String pattern;

    if (duration.isNegative()) {
        if (unit.isCalendrical()) {
            pattern = this.getPastPattern(amount, (CalendarUnit) unit);
        } else {
            pattern = this.getPastPattern(amount, (ClockUnit) unit);
        }
    } else {
        if (unit.isCalendrical()) {
            pattern = this.getFuturePattern(amount, (CalendarUnit) unit);
        } else {
            pattern = this.getFuturePattern(amount, (ClockUnit) unit);
        }
    }

    return this.format(pattern, amount);

}