List of usage examples for java.util.concurrent TimeUnit toMillis
public long toMillis(long duration)
From source file:tachyon.client.file.TachyonFileSystemUtils.java
/** * Wait for a file to be marked as completed. * <p/>//from w w w. ja v a 2s.com * The calling thread will block for <i>at most</i> {@code timeout} time units (as specified via * {@code tunit} or until the TachyonFile is reported as complete by the master. The method will * return the last known completion status of the file (hence, false only if the method has timed * out). A zero value on the {@code timeout} parameter will make the calling thread check once and * return; a negative value will make it block indefinitely. Note that, in this last case, if a * file is never completed, the thread will block forever, so use with care. * <p/> * Note that the file whose uri is specified, might not exist at the moment this method this call. * The method will deliberately block anyway for the specified amount of time, waiting for the * file to be created and eventually completed. Note also that the file might be moved or deleted * while it is waited upon. In such cases the method will throw the a {@link TachyonException} * with the appropriate {@link tachyon.exception.TachyonExceptionType} * <p/> * <i>IMPLEMENTATION NOTES</i> This method is implemented by periodically polling the master about * the file status. The polling period is controlled by the * {@link Constants#USER_FILE_WAITCOMPLETED_POLL_MS} java property and defaults to a generous 1 * second. * * @param tfs an instance of {@link TachyonFileSystemCore} * @param uri the URI of the file whose completion status is to be watied for * @param timeout maximum time the calling thread should be blocked on this call * @param tunit the @{link TimeUnit} instance describing the {@code timeout} parameter * @return true if the file is complete when this method returns and false if the method timed out * before the file was complete. * @throws IOException in case there are problems contacting the Tachyonmaster for the file status * @throws TachyonException if a Tachyon Exception occurs * @throws InterruptedException if the thread receives an interrupt while waiting for file * completion */ public static boolean waitCompleted(final TachyonFileSystemCore tfs, final TachyonURI uri, final long timeout, final TimeUnit tunit) throws IOException, TachyonException, InterruptedException { final long deadline = System.currentTimeMillis() + tunit.toMillis(timeout); final long pollPeriod = ClientContext.getConf().getLong(Constants.USER_FILE_WAITCOMPLETED_POLL_MS); TachyonFile file = null; boolean completed = false; long timeleft = deadline - System.currentTimeMillis(); long toSleep = 0; while (!completed && (timeout <= 0 || timeleft > 0)) { if (file == null) { file = tfs.openIfExists(uri, OpenOptions.defaults()); if (file == null) { LOG.debug( "The file {} being waited upon does not exist yet. Waiting for it to be " + "created.", uri); } } if (file != null) { completed = tfs.getInfo(file, GetInfoOptions.defaults()).isCompleted; } if (timeout == 0) { return completed; } else if (!completed) { if (timeout < 0 || timeleft > pollPeriod) { toSleep = pollPeriod; } else { toSleep = timeleft; } CommonUtils.sleepMs(LOG, toSleep, true); timeleft = deadline - System.currentTimeMillis(); } } return completed; }
From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java
private static long waitFor(Supplier<Boolean> condition, long duration, TimeUnit unit) throws Exception { StopWatch watch = new StopWatch(); watch.start();/*from w ww . ja v a 2 s . c o m*/ long timeout = unit.toMillis(duration); while (!condition.get()) { Thread.sleep(1_000); if (watch.getTime() > timeout) { throw new TimeoutException("Condition not reached in " + duration + " " + unit); } } return watch.getTime(); }
From source file:com.yihaodian.architecture.zkclient.TestUtil.java
/** * This waits until the provided {@link Callable} returns an object that is equals to the given expected value or * the timeout has been reached. In both cases this method will return the return value of the latest * {@link Callable} execution./* w w w.j a v a2 s.c om*/ * * @param expectedValue * The expected value of the callable. * @param callable * The callable. * @param <T> * The return type of the callable. * @param timeUnit * The timeout timeunit. * @param timeout * The timeout. * @return the return value of the latest {@link Callable} execution. * @throws Exception * @throws InterruptedException */ public static <T> T waitUntil(T expectedValue, Callable<T> callable, TimeUnit timeUnit, long timeout) throws Exception { long startTime = System.currentTimeMillis(); do { T actual = callable.call(); if (expectedValue.equals(actual)) { return actual; } if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { return actual; } Thread.sleep(50); } while (true); }
From source file:com.api6.zkclient.util.TestUtil.java
/** * callableexpectedValue//from w ww .java2 s. c o m * @param expectedValue * @param callable * @param timeUnit * @param timeout * @throws Exception * @return T callable */ public static <T> T waitUntil(T expectedValue, Callable<T> callable, TimeUnit timeUnit, long timeout) throws Exception { long startTime = System.currentTimeMillis(); do { T actual = callable.call(); if (expectedValue.equals(actual)) { System.out.println("TestUtil.waitUntil expected"); return actual; } if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { System.out.println("TestUtil.waitUntil timeout!"); return actual; } Thread.sleep(300); } while (true); }
From source file:org.cloudifysource.esc.installer.AgentlessInstaller.java
/******* * Checks if a TCP connection to a remote machine and port is possible. * //from w ww .j a va 2 s.com * @param ip * remote machine ip. * @param port * remote machine port. * @param installerConfiguration * . * @param timeout * duration to wait for successful connection. * @param unit * time unit to wait. * @throws InstallerException . * @throws TimeoutException . * @throws InterruptedException . */ public static void checkConnection(final String ip, final int port, final CloudTemplateInstallerConfiguration installerConfiguration, final long timeout, final TimeUnit unit) throws TimeoutException, InterruptedException, InstallerException { final long end = System.currentTimeMillis() + unit.toMillis(timeout); final InetAddress inetAddress = waitForRoute(installerConfiguration, ip, Math.min(end, System.currentTimeMillis() + installerConfiguration.getConnectionTestRouteResolutionTimeoutMillis())); final InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, port); logger.fine("Checking connection to: " + socketAddress); while (System.currentTimeMillis() + installerConfiguration.getConnectionTestIntervalMillis() < end) { // need to sleep since sock.connect may return immediately, and // server may take time to start Thread.sleep(installerConfiguration.getConnectionTestIntervalMillis()); final Socket sock = new Socket(); try { sock.connect(socketAddress, installerConfiguration.getConnectionTestConnectTimeoutMillis()); return; } catch (final IOException e) { logger.log(Level.FINE, "Checking connection to: " + socketAddress, e); // retry } finally { if (sock != null) { try { sock.close(); } catch (final IOException e) { logger.fine("Failed to close socket"); } } } } //timeout was reached String ipAddress = inetAddress.getHostAddress(); //if resolving fails we don't reach this line throw new TimeoutException("Failed connecting to " + IPUtils.getSafeIpAddress(ipAddress) + ":" + port); }
From source file:com.yihaodian.architecture.zkclient.TestUtil.java
/** * This waits until a mockito verification passed (which is provided in the runnable). This waits until the * virification passed or the timeout has been reached. If the timeout has been reached this method will rethrow the * {@link MockitoAssertionError} that comes from the mockito verification code. * /* w w w . ja v a 2 s . c om*/ * @param runnable * The runnable containing the mockito verification. * @param timeUnit * The timeout timeunit. * @param timeout * The timeout. * @throws InterruptedException */ public static void waitUntilVerified(Runnable runnable, TimeUnit timeUnit, int timeout) throws InterruptedException { long startTime = System.currentTimeMillis(); do { MockitoAssertionError exception = null; try { runnable.run(); } catch (MockitoAssertionError e) { exception = e; } if (exception == null) { return; } if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { throw exception; } Thread.sleep(50); } while (true); }
From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java
public static Future<Boolean> rockBlockIsReachable() { return new Future<Boolean>() { Boolean result = null;/*w w w . j a v a2s . co m*/ boolean canceled = false; long start = System.currentTimeMillis(); { if (System.currentTimeMillis() - lastSuccess < 15000) { result = true; } try { URL url = new URL("https://secure.rock7mobile.com/rockblock"); int len = url.openConnection().getContentLength(); if (len > 0) lastSuccess = System.currentTimeMillis(); result = len > 0; } catch (Exception e) { NeptusLog.pub().error(e); result = false; } } @Override public Boolean get() throws InterruptedException, ExecutionException { while (result == null) { Thread.sleep(100); } return result; } @Override public boolean cancel(boolean mayInterruptIfRunning) { canceled = true; return false; } @Override public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { while (result == null) { Thread.sleep(100); if (System.currentTimeMillis() - start > unit.toMillis(timeout)) throw new TimeoutException("Time out while connecting"); } return result; } @Override public boolean isCancelled() { return canceled; } @Override public boolean isDone() { return result != null; } }; }
From source file:org.openspaces.grid.gsm.containers.ContainersSlaUtils.java
static FutureGridServiceContainer startGridServiceContainerAsync(final InternalAdmin admin, final InternalGridServiceAgent gsa, final GridServiceContainerConfig config, final Log logger, final long duration, final TimeUnit timeUnit) { final AtomicReference<Object> ref = new AtomicReference<Object>(null); final long startTimestamp = System.currentTimeMillis(); final long end = startTimestamp + timeUnit.toMillis(duration); admin.scheduleAdminOperation(new Runnable() { public void run() { try { final OperatingSystemStatistics operatingSystemStatistics = gsa.getMachine() .getOperatingSystem().getStatistics(); // get total free system memory + cached (without sigar returns -1) long freeBytes = operatingSystemStatistics.getActualFreePhysicalMemorySizeInBytes(); if (freeBytes <= 0) { // fallback - no sigar. Provides a pessimistic number since does not take into // account OS cache that can be allocated. freeBytes = operatingSystemStatistics.getFreePhysicalMemorySizeInBytes(); if (freeBytes <= 0) { // machine is probably going down. ref.set(new AdminException("Cannot determine machine " + machineToString(gsa.getMachine()) + " free memory.")); }//from www.j a v a 2 s . c o m } final long freeInMB = MemoryUnit.MEGABYTES.convert(freeBytes, MemoryUnit.BYTES); if (freeInMB < config.getMaximumJavaHeapSizeInMB()) { ref.set(new AdminException("Machine " + machineToString(gsa.getMachine()) + " free memory " + freeInMB + "MB is not enough to start a container with " + config.getMaximumJavaHeapSizeInMB() + "MB. Free machine memory or increase machine provisioning reservedMemoryPerMachine property.")); } else { ref.set(gsa.internalStartGridService(config)); } } catch (AdminException e) { ref.set(e); } catch (Throwable e) { logger.error("Unexpected Exception " + e.getMessage(), e); ref.set(e); } } }); FutureGridServiceContainer future = new FutureGridServiceContainer() { public boolean isTimedOut() { return System.currentTimeMillis() > end; } 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 GridServiceContainer get() throws ExecutionException, IllegalStateException, TimeoutException { Object result = ref.get(); if (getException() != null) { throw getException(); } GridServiceContainer container = null; if (result != null) { int agentId = (Integer) result; container = getGridServiceContainerInternal(agentId); //container could still be null if not discovered } if (container == null) { if (isTimedOut()) { throw new TimeoutException("Starting a new container took more than " + timeUnit.toSeconds(duration) + " seconds to complete."); } throw new IllegalStateException("Async operation is not done yet."); } return container; } public boolean isDone() { Object result = ref.get(); if (System.currentTimeMillis() > end) { return true; } if (result == null) { return false; } if (result instanceof Throwable) { return true; } GridServiceContainer container = getGridServiceContainerInternal((Integer) result); if (container != null) { return true; } return false; } public GridServiceContainer getGridServiceContainerInternal(int agentId) { for (GridServiceContainer container : admin.getGridServiceContainers()) { String agentUid = ((InternalGridServiceContainer) container).getAgentUid(); if (agentUid != null && agentUid.equals(gsa.getUid())) { if (agentId == container.getAgentId()) { return container; } } } return null; } public GridServiceAgent getGridServiceAgent() { return gsa; } public GridServiceContainerConfig getGridServiceContainerConfig() { return config; } public Date getTimestamp() { return new Date(startTimestamp); } @Override public int getAgentId() throws ExecutionException, TimeoutException { ExecutionException exception = getException(); if (exception != null) { throw exception; } if (isTimedOut() && ref.get() == null) { throw new TimeoutException( "Starting a new container on machine " + gsa.getMachine().getHostAddress() + " took more than " + timeUnit.toSeconds(duration) + " seconds to complete."); } if (ref.get() == null) { throw new IllegalStateException("Async operation is not done yet."); } return (Integer) ref.get(); } public boolean isStarted() { return ref.get() != null; } }; return future; }
From source file:com.googlecode.fightinglayoutbugs.helpers.TestHelper.java
/** * Repetitively runs the given <code>runnableAssert</code> until it * succeeds without throwing an exception or error or until the * given <code>timeout</code> is reached. * * @throws TimeoutException if the given <code>runnableAssert</code> could not be executed successfully in the given time *///www .j a va 2 s. co m public static void waitFor(long timeout, TimeUnit timeoutUnit, RunnableAssert runnableAssert) { boolean success = false; final long timeoutReached = System.currentTimeMillis() + timeoutUnit.toMillis(timeout); do { try { runnableAssert.run(); success = true; } catch (Exception e) { if (System.currentTimeMillis() > timeoutReached) { AssertionError assertionError = new AssertionError( "Timeout while waiting for: " + runnableAssert + "."); assertionError.initCause(e); throw assertionError; } try { Thread.sleep(25); } catch (InterruptedException e2) { Thread.currentThread().interrupt(); throw new RuntimeException("Got interrupted while waiting for: " + runnableAssert + ".", e2); } } } while (!success); }
From source file:net.pms.io.ThreadedProcessWrapper.java
/** * Creates and runs a new {@link Process} in a new thread using the * specified commands. The process result is returned as a {@link Future} * {@link ByteProcessWrapperResult}.//from w ww .j a v a2s . com * * @param command the command(s) used to create the {@link Process}. * @param timeout the process timeout in {@code timeUnit}. * @param timeUnit the {@link TimeUnit} for {@code timeout}. * @param terminateTimeoutMS the timeout in milliseconds for each * termination attempt before a new attempt is made. * @return The process result as a {@link Future} * {@link ByteProcessWrapperResult}. */ @Nonnull public static Future<ByteProcessWrapperResult> runProcessByteOutput(@Nonnull List<String> command, long timeout, @Nonnull TimeUnit timeUnit, long terminateTimeoutMS) { return new ThreadedProcessWrapper<ByteProcessWrapperConsumer, ByteProcessWrapperResult, byte[]>( new ByteProcessWrapperConsumer()).runProcess(command, timeUnit.toMillis(timeout), terminateTimeoutMS); }