List of usage examples for java.util.concurrent TimeUnit toMillis
public long toMillis(long duration)
From source file:org.encos.flydown.limiters.cache.impl.RedisRatingCache.java
public boolean checkTooManyEntries(String evaluationKey, int maxCount, long timeRange, TimeUnit timeRangeUnit) { Long keyListLength = cacheTemplate.opsForList().size(evaluationKey); log.debug(MessageFormat.format("size([{0}])={1}, max={2}", evaluationKey, keyListLength, maxCount)); if (keyListLength > maxCount) { List<Object> values = cacheTemplate.opsForList().range(evaluationKey, 0, keyListLength - 1); Long firstEntry = (Long) values.get(0); Long lastEntry = (Long) values.get(values.size() - 1); return (lastEntry - firstEntry < timeRangeUnit.toMillis(timeRange)); }//from ww w .ja v a 2s.c om //not yet expired return false; }
From source file:net.pms.io.SimpleProcessWrapper.java
/** * Runs a process with the given command array. * * @param timeout the process timeout in {@code timeUnit} after which the * process is terminated. Use zero for no timeout, but be aware * of the <a href=/*w w w . j a va2 s. co m*/ * "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9" * >pitfalls</a> * @param timeUnit the {@link TimeUnit} for {@code timeout}. * @param terminateTimeoutMS the timeout in milliseconds to wait for each * termination attempt. * @param command the {@link String}s used to build the command line. * @return The {@link ProcessWrapperResult} from running the process. * @throws InterruptedException If the operation is interrupted. * @throws IllegalArgumentException If {@code command} is {@code null} or * empty. */ @Nonnull public R runProcess(long timeout, @Nonnull TimeUnit timeUnit, long terminateTimeoutMS, @Nonnull String... command) throws InterruptedException { return runProcess(Arrays.asList(command), timeUnit.toMillis(timeout), terminateTimeoutMS); }
From source file:org.cloudifysource.esc.driver.provisioning.storage.openstack.OpenstackStorageDriver.java
@Override public VolumeDetails createVolume(final String templateName, final String location, final long duration, final TimeUnit timeUnit) throws TimeoutException, StorageProvisioningException { final long endTime = System.currentTimeMillis() + timeUnit.toMillis(duration); final VolumeDetails volumeDetails = new VolumeDetails(); Volume volume;//from w ww . ja v a 2s . c o m //ignoring the passed location, it's a wrong format, taking the compute location instead Optional<? extends VolumeApi> volumeApi = getVolumeApi(); if (!volumeApi.isPresent()) { throw new StorageProvisioningException("Failed to create volume, Openstack API is not initialized."); } if (computeContext == null) { throw new StorageProvisioningException("Failed to create volume, compute context is not initialized."); } StorageTemplate storageTemplate = this.cloud.getCloudStorage().getTemplates().get(templateName); String volumeName = storageTemplate.getNamePrefix() + System.currentTimeMillis(); CreateVolumeOptions options = CreateVolumeOptions.Builder.name(volumeName).description(VOLUME_DESCRIPTION) .availabilityZone(getStorageZone(templateName)); volume = volumeApi.get().create(storageTemplate.getSize(), options); try { waitForVolumeToReachStatus(Volume.Status.AVAILABLE, volumeApi, volume.getId(), endTime); volume = volumeApi.get().get(volume.getId()); volumeDetails.setId(volume.getId()); volumeDetails.setName(volume.getName()); volumeDetails.setSize(volume.getSize()); volumeDetails.setLocation(volume.getZone()); logger.fine("Volume provisioned: " + volumeDetails.toString()); } catch (final Exception e) { logger.log(Level.WARNING, "volume: " + volume.getId() + " failed to start up correctly. Shutting it down." + " Error was: " + e.getMessage(), e); try { deleteVolume(region, volume.getId(), duration, timeUnit); } catch (final Exception e2) { logger.log(Level.WARNING, "Error while deleting volume: " + volume.getId() + ". Error was: " + e.getMessage() + ". It may be leaking.", e); } if (e instanceof TimeoutException) { throw (TimeoutException) e; } else { throw new StorageProvisioningException(e); } } return volumeDetails; }
From source file:com.codebullets.sagalib.timeout.InMemoryTimeoutManagerTest.java
private void requestAndTriggerTimeout(final String sagaId, final String name, final long delay, final TimeUnit unit, final Object data) { sut.requestTimeout(null, sagaId, delay, unit, name, data); ArgumentCaptor<SagaTimeoutTask> captor = ArgumentCaptor.forClass(SagaTimeoutTask.class); verify(executor).schedule(captor.capture(), eq(delay), eq(unit)); // move time forward by the expected delay Date oldDate = clock.now();//from w w w. ja v a 2 s. c o m when(clock.now()).thenReturn(new Date(oldDate.getTime() + unit.toMillis(delay))); SagaTimeoutTask timeoutTask = captor.getValue(); timeoutTask.run(); }
From source file:org.cloudifysource.esc.driver.provisioning.storage.aws.EbsStorageDriver.java
@Override public VolumeDetails createVolume(final String templateName, final String availabilityZone, final long duration, final TimeUnit timeUnit) throws TimeoutException, StorageProvisioningException { StorageTemplate storageTemplate = cloud.getCloudStorage().getTemplates().get(templateName); final long end = System.currentTimeMillis() + timeUnit.toMillis(duration); int size = storageTemplate.getSize(); if (size < MIN_VOLUME_SIZE || size > MAX_VOLUME_SIZE) { throw new StorageProvisioningException( "Volume size must be set to a value between " + MIN_VOLUME_SIZE + " and " + MAX_VOLUME_SIZE); }/*from w ww . j a v a2 s . co m*/ Volume volume = null; try { logger.fine("Creating new volume in availability zone " + availabilityZone + " of size " + size + " with prefix " + cloud.getCloudStorage().getTemplates().get(templateName).getNamePrefix()); volume = this.ebsClient.createVolumeInAvailabilityZone(availabilityZone, size); String volumeId = volume.getId(); logger.fine("Waiting for volume to become available."); waitForVolumeToReachStatus(Status.AVAILABLE, end, volumeId); logger.fine("Naming created volume with id " + volumeId); TagApi tagApi = getTagsApi(); Map<String, String> tagsMap = createTagsMap(templateName); tagApi.applyToResources(tagsMap, Arrays.asList(volumeId)); logger.fine("Volume created successfully. volume id is: " + volumeId); } catch (final Exception e) { if (volume != null) { handleExceptionAfterVolumeCreated(volume.getId()); } if (e instanceof TimeoutException) { throw (TimeoutException) e; } else { throw new StorageProvisioningException("Failed creating volume of size " + size + " in availability zone. " + availabilityZone + "Reason: " + e.getMessage(), e); } } return createVolumeDetails(volume); }
From source file:org.apache.accumulo.core.client.BatchWriterConfig.java
/** * Sets the maximum amount of time an unresponsive server will be re-tried. When this timeout is exceeded, the {@link BatchWriter} should throw an exception.<br> * For no timeout, set to zero, or {@link Long#MAX_VALUE} with {@link TimeUnit#MILLISECONDS}. * * <p>/*from w ww .j a v a 2 s . c om*/ * {@link TimeUnit#MICROSECONDS} or {@link TimeUnit#NANOSECONDS} will be truncated to the nearest {@link TimeUnit#MILLISECONDS}.<br> * If this truncation would result in making the value zero when it was specified as non-zero, then a minimum value of one {@link TimeUnit#MILLISECONDS} will * be used. * * <p> * <b>Default:</b> {@link Long#MAX_VALUE} (no timeout) * * @param timeout * the timeout, in the unit specified by the value of {@code timeUnit} * @param timeUnit * determines how {@code timeout} will be interpreted * @throws IllegalArgumentException * if {@code timeout} is less than 0 * @return {@code this} to allow chaining of set methods */ public BatchWriterConfig setTimeout(long timeout, TimeUnit timeUnit) { if (timeout < 0) throw new IllegalArgumentException("Negative timeout not allowed " + timeout); if (timeout == 0) this.timeout = Long.MAX_VALUE; else // make small, positive values that truncate to 0 when converted use the minimum millis instead this.timeout = Math.max(1, timeUnit.toMillis(timeout)); return this; }
From source file:com.netflix.governator.lifecycle.LifecycleManager.java
/** * The manager MUST be started. This version of start() has a maximum * wait period for warm up methods.//from www . j av a 2 s. c om * * @param maxWait maximum wait time for warm up methods - if the time elapses, the warm up methods are interrupted * @param unit time unit * @return true if warm up methods successfully executed, false if the time elapses * @throws Exception errors */ public boolean start(long maxWait, TimeUnit unit) throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTING), "Already started"); validate(); long maxMs = (unit != null) ? unit.toMillis(maxWait) : Long.MAX_VALUE; WarmUpSession warmUpSession = new WarmUpSession(getWarmUpDriver(), dagManager); boolean success = warmUpSession.doImmediate(maxMs); configurationDocumentation.output(log); configurationDocumentation.clear(); state.set(State.STARTED); return success; }
From source file:org.apache.accumulo.core.client.BatchWriterConfig.java
/** * Sets the maximum amount of time to hold the data in memory before flushing it to servers.<br> * For no maximum, set to zero, or {@link Long#MAX_VALUE} with {@link TimeUnit#MILLISECONDS}. * * <p>//from w w w. j a v a2 s . com * {@link TimeUnit#MICROSECONDS} or {@link TimeUnit#NANOSECONDS} will be truncated to the nearest {@link TimeUnit#MILLISECONDS}.<br> * If this truncation would result in making the value zero when it was specified as non-zero, then a minimum value of one {@link TimeUnit#MILLISECONDS} will * be used. * * <p> * <b>Default:</b> 120 seconds * * @param maxLatency * the maximum latency, in the unit specified by the value of {@code timeUnit} * @param timeUnit * determines how {@code maxLatency} will be interpreted * @throws IllegalArgumentException * if {@code maxLatency} is less than 0 * @return {@code this} to allow chaining of set methods */ public BatchWriterConfig setMaxLatency(long maxLatency, TimeUnit timeUnit) { if (maxLatency < 0) throw new IllegalArgumentException("Negative max latency not allowed " + maxLatency); if (maxLatency == 0) this.maxLatency = Long.MAX_VALUE; else // make small, positive values that truncate to 0 when converted use the minimum millis instead this.maxLatency = Math.max(1, timeUnit.toMillis(maxLatency)); return this; }
From source file:bear.core.AbstractConsole.java
public boolean awaitStreamCopiers(long duration, TimeUnit unit) { // logger.debug("OOOOOOOOOOOOPS - awaitStreamCopiers"); long periodNs = NANOSECONDS.convert(duration, unit) / 9; if (periodNs == 0) { periodNs = 1;//from www .j a v a 2 s .c o m } long sleepMs = MILLISECONDS.convert(periodNs, NANOSECONDS); long sleepNano = periodNs - NANOSECONDS.convert(sleepMs, MILLISECONDS); final long durationMs = unit.toMillis(duration); long startedAt = System.currentTimeMillis(); for (MyStreamCopier copier : copiers) { copier.setFinishAtMs(startedAt + durationMs); } while (true) { try { for (MyStreamCopier copier : copiers) { copier.triggerCopy(); } final long now = System.currentTimeMillis(); long timeElapsedMs = now - startedAt; if (allFinished()) { return true; } if (timeElapsedMs > durationMs) { return false; } Thread.sleep(sleepMs, (int) sleepNano); } catch (InterruptedException e) { throw Exceptions.runtime(e); } } }
From source file:org.apache.http.impl.conn.SingleClientConnManager.java
public void closeIdleConnections(final long idletime, final TimeUnit tunit) { assertStillUp();//from w w w. j av a 2 s . co m // idletime can be 0 or negative, no problem there Args.notNull(tunit, "Time unit"); synchronized (this) { if ((managedConn == null) && uniquePoolEntry.connection.isOpen()) { final long cutoff = System.currentTimeMillis() - tunit.toMillis(idletime); if (lastReleaseTime <= cutoff) { try { uniquePoolEntry.close(); } catch (final IOException iox) { // ignore log.debug("Problem closing idle connection.", iox); } } } } }