Java Code Examples for java.time.Duration#toMillis()

The following examples show how to use java.time.Duration#toMillis() . 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: DefaultClaimSet.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized boolean acquire(byte[] claimId, Duration ttl) {
    checkNotNull(claimId, "claimId");
    long ttlMillis = ttl.toMillis();
    checkArgument(ttlMillis >= 0, "Ttl must be >=0");

    long now = System.currentTimeMillis();
    processExpirationQueues(now);

    Claim claim = new Claim(claimId, ttlMillis, now + ttlMillis);
    if (_claimMap.containsKey(claim)) {
        return false;
    }

    _claimMap.put(claim, claim);
    addToExpirationQueue(claim);
    return true;
}
 
Example 2
Source File: PeriodFormats.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * A (localized) interval phrase like "X seconds" or "X minutes". Uses the largest unit that can
 * represent the interval precisely. This is useful when the interval is expected to be a "round"
 * value. The interval must be non-zero.
 */
public static Component briefNaturalPrecise(Duration duration) {
  if (duration.isZero() || duration.isNegative()) {
    throw new IllegalArgumentException("Duration must be positive");
  }

  long ms = duration.toMillis();
  for (TemporalUnit unit : UNITS) {
    if (ms % unit.getDuration().toMillis() == 0) {
      return formatPeriod(unit, periodAmount(unit, duration));
    }
  }
  throw new IllegalStateException();
}
 
Example 3
Source File: PlatformRecorder.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void writeMetaEvents() {

        if (activeRecordingEvent.isEnabled()) {
            for (PlatformRecording r : getRecordings()) {
                if (r.getState() == RecordingState.RUNNING && r.shouldWriteMetadataEvent()) {
                    ActiveRecordingEvent event = new ActiveRecordingEvent();
                    event.id = r.getId();
                    event.name = r.getName();
                    WriteableUserPath p = r.getDestination();
                    event.destination = p == null ? null : p.getText();
                    Duration d = r.getDuration();
                    event.recordingDuration = d == null ? Long.MAX_VALUE : d.toMillis();
                    Duration age = r.getMaxAge();
                    event.maxAge = age == null ? Long.MAX_VALUE : age.toMillis();
                    Long size = r.getMaxSize();
                    event.maxSize = size == null ? Long.MAX_VALUE : size;
                    Instant start = r.getStartTime();
                    event.recordingStart = start == null ? Long.MAX_VALUE : start.toEpochMilli();
                    event.commit();
                }
            }
        }
        if (activeSettingEvent.isEnabled()) {
            for (EventControl ec : MetadataRepository.getInstance().getEventControls()) {
                ec.writeActiveSettingEvent();
            }
        }
    }
 
Example 4
Source File: DefaultCache.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public long getCacheCulls(final Duration duration) {
    final long millis = duration.toMillis();
    if(millis > MAX_CULL_COUNT_PERIOD) {
        throw new IllegalArgumentException("Request duration exceed maximum of " + StringUtils.getFullElapsedTime(duration));
    }
    cullCacheTimes();
    final long oldestCullToCount = System.currentTimeMillis() - millis;
    return cullTimes.stream()
        .filter(cullTime -> cullTime >= oldestCullToCount)
        .count();
}
 
Example 5
Source File: PlatformRecorder.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void writeMetaEvents() {

        if (activeRecordingEvent.isEnabled()) {
            for (PlatformRecording r : getRecordings()) {
                if (r.getState() == RecordingState.RUNNING && r.shouldWriteMetadataEvent()) {
                    ActiveRecordingEvent event = new ActiveRecordingEvent();
                    event.id = r.getId();
                    event.name = r.getName();
                    WriteableUserPath p = r.getDestination();
                    event.destination = p == null ? null : p.getText();
                    Duration d = r.getDuration();
                    event.recordingDuration = d == null ? Long.MAX_VALUE : d.toMillis();
                    Duration age = r.getMaxAge();
                    event.maxAge = age == null ? Long.MAX_VALUE : age.toMillis();
                    Long size = r.getMaxSize();
                    event.maxSize = size == null ? Long.MAX_VALUE : size;
                    Instant start = r.getStartTime();
                    event.recordingStart = start == null ? Long.MAX_VALUE : start.toEpochMilli();
                    event.commit();
                }
            }
        }
        if (activeSettingEvent.isEnabled()) {
            for (EventControl ec : MetadataRepository.getInstance().getEventControls()) {
                ec.writeActiveSettingEvent();
            }
        }
    }
 
Example 6
Source File: PyramidPlunderTimer.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
public PyramidPlunderTimer(
	Duration duration,
	BufferedImage image,
	PyramidPlunderPlugin plugin,
	PyramidPlunderConfig config,
	Client client
)
{
	super(duration.toMillis(), ChronoUnit.MILLIS, image, plugin);
	this.config = config;
	this.client = client;
}
 
Example 7
Source File: StartPushChannel.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
public StartPushChannel(String address, Duration duration) {
        this();
        this.address = address;
        this.expiration = System.currentTimeMillis() + duration.toMillis();
//        this.params = new Params();
//        this.params.ttl = duration.getSeconds();
    }
 
Example 8
Source File: AggressionTimer.java    From runelite with BSD 2-Clause "Simplified" License 4 votes vote down vote up
AggressionTimer(Duration duration, BufferedImage image, Plugin plugin, boolean visible)
{
	super(duration.toMillis(), ChronoUnit.MILLIS, image, plugin);
	setTooltip("Time until NPCs become unaggressive");
	this.visible = visible;
}
 
Example 9
Source File: SynchronizedGeneratorIdentity.java    From java-uniqueid with Apache License 2.0 4 votes vote down vote up
static Long getDurationInMillis(Supplier<Duration> durationSupplier) {
    if (durationSupplier == null) return null;
    Duration duration = durationSupplier.get();
    if (duration == null) return null;
    return duration.toMillis();
}
 
Example 10
Source File: KeyDerivationTasks.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public KeyDerivationTasks(KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) {
    keyDerivationTask = new Task<KeyParameter>() {
        @Override
        protected KeyParameter call() throws Exception {
            long start = System.currentTimeMillis();
            try {
                log.info("Started key derivation");
                KeyParameter result = scrypt.deriveKey(password);
                timeTakenMsec = (int) (System.currentTimeMillis() - start);
                log.info("Key derivation done in {}ms", timeTakenMsec);
                return result;
            } catch (Throwable e) {
                log.error("Exception during key derivation", e);
                throw e;
            }
        }
    };

    // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100%
    // a brief moment after the keys were derived successfully.
    progressTask = new Task<Void>() {
        private KeyParameter aesKey;

        @Override
        protected Void call() throws Exception {
            if (targetTime != null) {
                long startTime = System.currentTimeMillis();
                long curTime;
                long targetTimeMillis = targetTime.toMillis();
                while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) {
                    double progress = (curTime - startTime) / (double) targetTimeMillis;
                    updateProgress(progress, 1.0);

                    // 60fps would require 16msec sleep here.
                    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
                }
                // Wait for the encryption thread before switching back to main UI.
                updateProgress(1.0, 1.0);
            } else {
                updateProgress(-1, -1);
            }
            aesKey = keyDerivationTask.get();
            return null;
        }

        @Override
        protected void succeeded() {
            checkGuiThread();
            onFinish(aesKey, timeTakenMsec);
        }
    };
    progress = progressTask.progressProperty();
}
 
Example 11
Source File: TCKDuration.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=ArithmeticException.class)
public void test_toMillis_tooBig() {
    Duration test = Duration.ofSeconds(Long.MAX_VALUE / 1000, ((Long.MAX_VALUE % 1000) + 1) * 1000000);
    test.toMillis();
}
 
Example 12
Source File: Evaluator.java    From sofa-lookout with Apache License 2.0 4 votes vote down vote up
private static long durationMilliseconds(Duration offset) {
    return offset.toMillis();
}
 
Example 13
Source File: AbstractAtomicMapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public DistributedSet<Entry<K, Versioned<byte[]>>> sync(Duration operationTimeout) {
  return new BlockingDistributedSet<>(this, operationTimeout.toMillis());
}
 
Example 14
Source File: OpenSSLFactory.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Sets the session cache timeout
 */
public void setSessionCacheTimeout(Duration period)
{
  _sessionCacheTimeout = (int) (period.toMillis() / 1000);
}
 
Example 15
Source File: AtomicMultimapProxy.java    From atomix with Apache License 2.0 4 votes vote down vote up
@Override
public DistributedMultiset<byte[]> sync(Duration operationTimeout) {
  return new BlockingDistributedMultiset<>(this, operationTimeout.toMillis());
}
 
Example 16
Source File: TitheFarmPlant.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
double getPlantTimeRelative()
{
	Duration duration = Duration.between(planted, Instant.now());
	return duration.compareTo(PLANT_TIME) < 0 ? (double) duration.toMillis() / PLANT_TIME.toMillis() : 1;
}
 
Example 17
Source File: PolledMeter.java    From spectator with Apache License 2.0 2 votes vote down vote up
/**
 * Set the delay at which the value should be refreshed. If not set, then
 * the default value will be the gauge polling frequency set in the registry
 * configuration.
 *
 * @see
 *     com.netflix.spectator.api.RegistryConfig#gaugePollingFrequency()
 *
 * @return
 *     This builder instance to allow chaining of operations.
 */
public Builder withDelay(Duration delay) {
  this.delay = delay.toMillis();
  return this;
}
 
Example 18
Source File: HunterTrap.java    From runelite with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Calculates how much time is left before the trap is collapsing.
 *
 * @return Value between 0 and 1. 0 means the trap was laid moments ago.
 * 1 is a trap that's about to collapse.
 */
public double getTrapTimeRelative()
{
	Duration duration = Duration.between(placedOn, Instant.now());
	return duration.compareTo(TRAP_TIME) < 0 ? (double) duration.toMillis() / TRAP_TIME.toMillis() : 1;
}
 
Example 19
Source File: HttpUrlConnectionSender.java    From micrometer with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a sender with the specified timeouts and proxy settings.
 *
 * @param connectTimeout connect timeout when establishing a connection
 * @param readTimeout read timeout when receiving a response
 * @param proxy proxy to use when establishing a connection
 * @since 1.2.0
 */
public HttpUrlConnectionSender(Duration connectTimeout, Duration readTimeout, Proxy proxy) {
    this.connectTimeoutMs = (int) connectTimeout.toMillis();
    this.readTimeoutMs = (int) readTimeout.toMillis();
    this.proxy = proxy;
}
 
Example 20
Source File: MarketData.java    From FX-AlgorithmTrading with MIT License 2 votes vote down vote up
/**
 * MarketTimeとレート受信時刻との差をミリ秒単位で返します。
 *
 * @return long ミリ秒レイテンシー
 */
public long calcLatency() {
    Duration duration = Duration.between(marketDateTime, getCreateDateTime());
    return duration.toMillis();
}