List of usage examples for java.util.concurrent TimeUnit toMillis
public long toMillis(long duration)
From source file:org.apache.ogt.http.impl.conn.SingleClientConnManager.java
public synchronized void closeIdleConnections(long idletime, TimeUnit tunit) { assertStillUp();/*from ww w . jav a 2s. c o m*/ // idletime can be 0 or negative, no problem there if (tunit == null) { throw new IllegalArgumentException("Time unit must not be null."); } if ((managedConn == null) && uniquePoolEntry.connection.isOpen()) { final long cutoff = System.currentTimeMillis() - tunit.toMillis(idletime); if (lastReleaseTime <= cutoff) { try { uniquePoolEntry.close(); } catch (IOException iox) { // ignore log.debug("Problem closing idle connection.", iox); } } } }
From source file:org.cloudifysource.shell.installer.ManagementWebServiceInstaller.java
/** * {@inheritDoc}//from ww w. j a v a 2s. c om */ @Override public void waitForInstallation(final AdminFacade adminFacade, final GridServiceAgent agent, final long timeout, final TimeUnit timeunit) throws InterruptedException, TimeoutException, CLIException { final long startTime = System.currentTimeMillis(); final URL url = waitForProcessingUnitInstance(agent, timeout, timeunit); final long remainingTime = timeunit.toMillis(timeout) - (System.currentTimeMillis() - startTime); if (waitForConnection) { waitForConnection(adminFacade, username, password, url, remainingTime, TimeUnit.MILLISECONDS); } }
From source file:ai.eve.volley.Request.java
/** * Set how long the cache is expired, {@link ai.eve.volley.cache.DiskCache} * will determine the cache entry is expired or not. For example : * Request.setCacheExpireTime(TimeUnit.MINUTES, 1); // cache stays one * minute Request.setCacheExpireTime(TimeUnit.DAYS, 2); // cache stays two * days/*from w w w .j a v a 2 s . c o m*/ * * @param timeUnit * what unit for the amount value * @param amount * how much unit should calculate */ public void setCacheExpireTime(TimeUnit timeUnit, int amount) { this.mCacheExpireTime = System.currentTimeMillis() + timeUnit.toMillis(amount); }
From source file:com.linkedin.pinot.core.segment.index.SegmentMetadataImpl.java
private void setTimeIntervalAndGranularity() { if (_segmentMetadataPropertiesConfiguration.containsKey(V1Constants.MetadataKeys.Segment.SEGMENT_START_TIME) && _segmentMetadataPropertiesConfiguration .containsKey(V1Constants.MetadataKeys.Segment.SEGMENT_END_TIME) && _segmentMetadataPropertiesConfiguration .containsKey(V1Constants.MetadataKeys.Segment.TIME_UNIT)) { try {/*from www. ja va 2 s. com*/ TimeUnit segmentTimeUnit = TimeUtils .timeUnitFromString(_segmentMetadataPropertiesConfiguration.getString(TIME_UNIT)); _timeGranularity = new Duration(segmentTimeUnit.toMillis(1)); String startTimeString = _segmentMetadataPropertiesConfiguration .getString(V1Constants.MetadataKeys.Segment.SEGMENT_START_TIME); String endTimeString = _segmentMetadataPropertiesConfiguration .getString(V1Constants.MetadataKeys.Segment.SEGMENT_END_TIME); _timeInterval = new Interval(segmentTimeUnit.toMillis(Long.parseLong(startTimeString)), segmentTimeUnit.toMillis(Long.parseLong(endTimeString))); } catch (Exception e) { LOGGER.warn("Caught exception while setting time interval and granularity", e); _timeInterval = null; _timeGranularity = null; } } }
From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java
@Override public FutureGridServiceAgents getDiscoveredMachinesAsync(final long duration, final TimeUnit unit) { final AtomicReference<Object> ref = new AtomicReference<Object>(null); final long start = System.currentTimeMillis(); final long end = start + unit.toMillis(duration); submit(new Runnable() { public void run() { try { GridServiceAgent[] agents = machineProvisioning.getDiscoveredMachines(duration, unit); ref.set(agents);// www.jav a 2s . co m } catch (ElasticMachineProvisioningException e) { ref.set(e); } catch (ElasticGridServiceAgentProvisioningException e) { ref.set(e); } catch (InterruptedException e) { ref.set(e); } catch (TimeoutException e) { ref.set(e); } catch (NoClassDefFoundError e) { ref.set((new NoClassDefFoundElasticMachineProvisioningException(e))); } catch (Throwable e) { logger.error("Unexpected exception", e); ref.set(e); } } }); return new FutureGridServiceAgents() { public boolean isDone() { return System.currentTimeMillis() > end || ref.get() != null; } public ExecutionException getException() { Object result = ref.get(); if (result != null && result instanceof Throwable) { Throwable throwable = (Throwable) result; return new ExecutionException(throwable.getMessage(), throwable); } return null; } public boolean isTimedOut() { Object result = ref.get(); return System.currentTimeMillis() > end || (result != null && result instanceof TimeoutException); } public Date getTimestamp() { return new Date(start); } public GridServiceAgent[] get() throws ExecutionException, IllegalStateException, TimeoutException { Object result = ref.get(); if (result == null) { if (System.currentTimeMillis() > end) { throw new TimeoutException("Starting a new machine took more than " + unit.toSeconds(duration) + " seconds to complete."); } throw new IllegalStateException("Async operation is not done yet."); } if (getException() != null) { throw getException(); } return (GridServiceAgent[]) result; } }; }
From source file:org.alfresco.bm.api.v1.ResultsRestAPI.java
/** * Retrieve an approximate number of results, allowing for a smoothing factor * (<a href=http://en.wikipedia.org/wiki/Moving_average#Simple_moving_average>Simple Moving Average</a>) - * the number of data results to including in the moving average. * /*w w w. j a v a 2s . c o m*/ * @param fromTime the approximate time to start from * @param timeUnit the units of the 'reportPeriod' (default SECONDS). See {@link TimeUnit}. * @param reportPeriod how often a result should be output. This is expressed as a multiple of the 'timeUnit'. * @param smoothing the number of results to include in the Simple Moving Average calculations * @param chartOnly <tt>true</tt> to filter out results that are not of interest in performance charts * * @return JSON representing the event start time (x-axis) and the smoothed average execution time * along with data such as the events per second, failures per second, etc. */ @GET @Path("/ts") @Produces(MediaType.APPLICATION_JSON) public String getTimeSeriesResults(@DefaultValue("0") @QueryParam("fromTime") long fromTime, @DefaultValue("SECONDS") @QueryParam("timeUnit") String timeUnit, @DefaultValue("1") @QueryParam("reportPeriod") long reportPeriod, @DefaultValue("1") @QueryParam("smoothing") int smoothing, @DefaultValue("true") @QueryParam("chartOnly") boolean chartOnly) { if (logger.isDebugEnabled()) { logger.debug("Inbound: " + "[test:" + test + ",fromTime:" + fromTime + ",timeUnit:" + timeUnit + ",reportPeriod:" + reportPeriod + ",smoothing:" + smoothing + ",chartOnly:" + chartOnly + "]"); } if (reportPeriod < 1) { throwAndLogException(Status.BAD_REQUEST, "'reportPeriod' must be 1 or more."); } if (smoothing < 1) { throwAndLogException(Status.BAD_REQUEST, "'smoothing' must be 1 or more."); } TimeUnit timeUnitEnum = null; try { timeUnitEnum = TimeUnit.valueOf(timeUnit.toUpperCase()); } catch (Exception e) { // Invalid time unit throwAndLogException(Status.BAD_REQUEST, e); } final ResultService resultService = getResultService(); // Calculate the window size long reportPeriodMs = timeUnitEnum.toMillis(reportPeriod); long windowSize = reportPeriodMs * smoothing; // This is just too convenient an API final BasicDBList events = new BasicDBList(); ResultHandler handler = new ResultHandler() { @Override public boolean processResult(long fromTime, long toTime, Map<String, DescriptiveStatistics> statsByEventName, Map<String, Integer> failuresByEventName) throws Throwable { for (Map.Entry<String, DescriptiveStatistics> entry : statsByEventName.entrySet()) { String eventName = entry.getKey(); DescriptiveStatistics stats = entry.getValue(); Integer failures = failuresByEventName.get(eventName); if (failures == null) { logger.error("Found null failure count: " + entry); // Do nothing with it and stop return false; } // Per second double numPerSec = (double) stats.getN() / ((double) (toTime - fromTime) / 1000.0); double failuresPerSec = (double) failures / ((double) (toTime - fromTime) / 1000.0); // Push into an object DBObject eventObj = BasicDBObjectBuilder.start().add("time", toTime).add("name", eventName) .add("mean", stats.getMean()).add("min", stats.getMin()).add("max", stats.getMax()) .add("stdDev", stats.getStandardDeviation()).add("num", stats.getN()) .add("numPerSec", numPerSec).add("fail", failures).add("failPerSec", failuresPerSec) .get(); // Add the object to the list of events events.add(eventObj); } // Go for the next result return true; } }; try { // Get all the results resultService.getResults(handler, fromTime, windowSize, reportPeriodMs, chartOnly); // Muster into JSON String json = events.toString(); // Done if (logger.isDebugEnabled()) { int jsonLen = json.length(); if (jsonLen < 500) { logger.debug("Outbound: " + json); } else { logger.debug("Outbound: " + json.substring(0, 250) + " ... " + json.substring(jsonLen - 250, jsonLen)); } } return json; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throwAndLogException(Status.INTERNAL_SERVER_ERROR, e); return null; } }
From source file:org.openspaces.admin.internal.space.DefaultSpace.java
public synchronized void setStatisticsInterval(long interval, TimeUnit timeUnit) { statisticsInterval = timeUnit.toMillis(interval); if (isMonitoring()) { rescheduleStatisticsMonitor();// w w w. j a v a 2 s . co m } for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.setStatisticsInterval(interval, timeUnit); } }
From source file:org.openspaces.grid.gsm.rebalancing.RebalancingUtils.java
static Collection<FutureStatelessProcessingUnitInstance> incrementNumberOfStatelessInstancesAsync( final ProcessingUnit pu, final GridServiceContainer[] containers, final Log logger, final long duration, final TimeUnit timeUnit) { if (pu.getMaxInstancesPerVM() != 1) { throw new IllegalArgumentException("Only one instance per VM is allowed"); }//from w w w .j a v a2s. com List<GridServiceContainer> unusedContainers = getUnusedContainers(pu, containers); final Admin admin = pu.getAdmin(); final Map<GridServiceContainer, FutureStatelessProcessingUnitInstance> futureInstances = new HashMap<GridServiceContainer, FutureStatelessProcessingUnitInstance>(); final AtomicInteger targetNumberOfInstances = new AtomicInteger(pu.getNumberOfInstances()); final long start = System.currentTimeMillis(); final long end = start + timeUnit.toMillis(duration); for (GridServiceContainer container : unusedContainers) { final GridServiceContainer targetContainer = container; futureInstances.put(container, new FutureStatelessProcessingUnitInstance() { AtomicReference<Throwable> throwable = new AtomicReference<Throwable>(); ProcessingUnitInstance newInstance; public boolean isTimedOut() { return System.currentTimeMillis() > end; } public boolean isDone() { end(); return isTimedOut() || throwable.get() != null || newInstance != null; } public ProcessingUnitInstance get() throws ExecutionException, IllegalStateException, TimeoutException { end(); if (getException() != null) { throw getException(); } if (newInstance == null) { if (isTimedOut()) { throw new TimeoutException("Relocation timeout"); } throw new IllegalStateException("Async operation is not done yet."); } return newInstance; } public Date getTimestamp() { return new Date(start); } public ExecutionException getException() { end(); Throwable t = throwable.get(); if (t != null) { return new ExecutionException(t.getMessage(), t); } return null; } public GridServiceContainer getTargetContainer() { return targetContainer; } public ProcessingUnit getProcessingUnit() { return pu; } public String getFailureMessage() throws IllegalStateException { if (isTimedOut()) { return "deployment timeout of processing unit " + pu.getName() + " on " + gscToString(targetContainer); } if (getException() != null) { return getException().getMessage(); } throw new IllegalStateException("Relocation has not encountered any failure."); } private void end() { if (!targetContainer.isDiscovered()) { throwable.set(new RemovedContainerProcessingUnitDeploymentException(pu, targetContainer)); } else if (throwable.get() != null || newInstance != null) { //do nothing. idempotent method } else { incrementInstance(); ProcessingUnitInstance[] instances = targetContainer .getProcessingUnitInstances(pu.getName()); if (instances.length > 0) { newInstance = instances[0]; } } } private void incrementInstance() { final String uuid = "[incrementUid:" + UUID.randomUUID().toString() + "] "; int numberOfInstances = pu.getNumberOfInstances(); int maxNumberOfInstances = getContainersOnMachines(pu).length; if (numberOfInstances < maxNumberOfInstances) { if (targetNumberOfInstances.get() == numberOfInstances + 1) { if (logger.isInfoEnabled()) { logger.info("Waiting for pu.numberOfInstances to increment from " + numberOfInstances + " to " + targetNumberOfInstances.get() + ". " + "Number of relevant containers " + maxNumberOfInstances); } } else if (admin.getGridServiceManagers().getSize() > 1 && !((InternalProcessingUnit) pu).isBackupGsmInSync()) { if (logger.isInfoEnabled()) { logger.info("Waiting for backup gsm to sync with active gsm"); } } else { targetNumberOfInstances.set(numberOfInstances + 1); if (logger.isInfoEnabled()) { logger.info(uuid + " Planning to increment pu.numberOfInstances from " + numberOfInstances + " to " + targetNumberOfInstances.get() + ". " + "Number of relevant containers " + maxNumberOfInstances); } ((InternalAdmin) admin).scheduleAdminOperation(new Runnable() { public void run() { try { // this is an async operation // pu.getNumberOfInstances() still shows the old value. pu.incrementInstance(); if (logger.isInfoEnabled()) { logger.info(uuid + " pu.incrementInstance() called"); } } catch (AdminException e) { throwable.set(e); } catch (Throwable e) { logger.error(uuid + " Unexpected Exception: " + e.getMessage(), e); throwable.set(e); } } }); } } } }); } return futureInstances.values(); }
From source file:org.apache.http2.impl.conn.SingleClientConnManager.java
public void closeIdleConnections(long idletime, TimeUnit tunit) { assertStillUp();//from w w w. jav a2 s .c o m // idletime can be 0 or negative, no problem there if (tunit == null) { throw new IllegalArgumentException("Time unit must not be null."); } synchronized (this) { if ((managedConn == null) && uniquePoolEntry.connection.isOpen()) { final long cutoff = System.currentTimeMillis() - tunit.toMillis(idletime); if (lastReleaseTime <= cutoff) { try { uniquePoolEntry.close(); } catch (IOException iox) { // ignore log.debug("Problem closing idle connection.", iox); } } } } }
From source file:com.legstar.protobuf.cobol.ProtoCobol.java
/** * From Google's org.waveprotocol.pst.PstFileDescriptor. * <p/>/*from w w w .j a va 2s . com*/ * Will kill a process if it takes too long. * * @param delay how long to wait ( * @param unit the unit of time delay is expressed in * @param process the process to kill */ protected void killProcessAfter(final long delay, final TimeUnit unit, final Process process) { Thread processKiller = new Thread() { @Override public void run() { try { Thread.sleep(unit.toMillis(delay)); process.destroy(); } catch (InterruptedException e) { } } }; processKiller.setDaemon(true); processKiller.start(); }