Java Code Examples for java.util.concurrent.TimeUnit#toMillis()

The following examples show how to use java.util.concurrent.TimeUnit#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: RedissonMultiLock.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {
    long baseWaitTime = locks.size() * 1500;
    long waitTime = -1;
    if (leaseTime == -1) {
        waitTime = baseWaitTime;
    } else {
        leaseTime = unit.toMillis(leaseTime);
        waitTime = leaseTime;
        if (waitTime <= 2000) {
            waitTime = 2000;
        } else if (waitTime <= baseWaitTime) {
            waitTime = ThreadLocalRandom.current().nextLong(waitTime/2, waitTime);
        } else {
            waitTime = ThreadLocalRandom.current().nextLong(baseWaitTime, waitTime);
        }
    }
    
    while (true) {
        if (tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS)) {
            return;
        }
    }
}
 
Example 2
Source File: AppDeployerIT.java    From spring-cloud-deployer-yarn with Apache License 2.0 6 votes vote down vote up
private ApplicationId assertWaitApp(long timeout, TimeUnit unit, YarnCloudAppService yarnCloudAppService) throws Exception {
	ApplicationId applicationId = null;
	Collection<CloudAppInstanceInfo> instances;
	long end = System.currentTimeMillis() + unit.toMillis(timeout);

	do {
		instances = yarnCloudAppService.getInstances(CloudAppType.STREAM);
		if (instances.size() == 1) {
			CloudAppInstanceInfo cloudAppInstanceInfo = instances.iterator().next();
			if (StringUtils.hasText(cloudAppInstanceInfo.getAddress())) {
				applicationId = ConverterUtils.toApplicationId(cloudAppInstanceInfo.getApplicationId());
				break;
			}
		}
		Thread.sleep(1000);
	} while (System.currentTimeMillis() < end);

	assertThat(applicationId, notNullValue());
	return applicationId;
}
 
Example 3
Source File: FutureImpl.java    From msgpack-rpc-java with Apache License 2.0 6 votes vote down vote up
void join(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
    long end_time = System.currentTimeMillis() + unit.toMillis(timeout);
    boolean run_callback = false;
    synchronized (lock) {
        while (done == false) {
            long timeout_remaining = end_time - System.currentTimeMillis();
            if (timeout_remaining <= 0) break;
            lock.wait(timeout_remaining);
        }
        if (!done) {
            this.error = ValueFactory.createRawValue("timedout");
            done = true;
            lock.notifyAll();
            run_callback = true;
        }
    }
    if (run_callback && callback != null) {
        // FIXME #SF submit?
        // session.getEventLoop().getWorkerExecutor().submit(callback);
        callback.run();
    }
}
 
Example 4
Source File: PoolEntry.java    From java-android-websocket-client with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new {@code PoolEntry} instance.
 *
 * @param id unique identifier of the pool entry. May be {@code null}.
 * @param route route to the opposite endpoint.
 * @param conn the connection.
 * @param timeToLive maximum time to live. May be zero if the connection
 *   does not have an expiry deadline.
 * @param tunit time unit.
 */
public PoolEntry(final String id, final T route, final C conn,
        final long timeToLive, final TimeUnit tunit) {
    super();
    Args.notNull(route, "Route");
    Args.notNull(conn, "Connection");
    Args.notNull(tunit, "Time unit");
    this.id = id;
    this.route = route;
    this.conn = conn;
    this.created = System.currentTimeMillis();
    this.updated = this.created;
    if (timeToLive > 0) {
        this.validityDeadline = this.created + tunit.toMillis(timeToLive);
    } else {
        this.validityDeadline = Long.MAX_VALUE;
    }
    this.expiry = this.validityDeadline;
}
 
Example 5
Source File: AbstractCliBootYarnClusterTests.java    From spring-cloud-deployer-yarn with Apache License 2.0 6 votes vote down vote up
protected ApplicationInfo waitState(ApplicationId applicationId, long timeout, TimeUnit unit, YarnApplicationState... applicationStates) throws Exception {
	YarnApplicationState state = null;
	ApplicationReport report = null;
	long end = System.currentTimeMillis() + unit.toMillis(timeout);

	// break label for inner loop
	done:
	do {
		report = findApplicationReport(getYarnClient(), applicationId);
		if (report == null) {
			break;
		}
		state = report.getYarnApplicationState();
		for (YarnApplicationState stateCheck : applicationStates) {
			if (state.equals(stateCheck)) {
				break done;
			}
		}
		Thread.sleep(1000);
	} while (System.currentTimeMillis() < end);
	return new ApplicationInfo(applicationId, report);
}
 
Example 6
Source File: FuseAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private JMXConnector getJMXConnector(long timeout, TimeUnit unit, String username, String password) throws Exception {
    Exception lastException = null;
    long timeoutMillis = System.currentTimeMillis() + unit.toMillis(timeout);
    while (System.currentTimeMillis() < timeoutMillis) {
        try {
            Map<String, ?> env = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[] { username, password });
            return JMXConnectorFactory.connect(new JMXServiceURL(getJmxServiceUrl()), env);
        } catch (Exception ex) {
            lastException = ex;
            Thread.sleep(500);
            log.debug("Loop: Getting MBean Server Connection: last caught exception: " + lastException.getClass().getName());
        }
    }
    log.error("Failed to get MBean Server Connection within " + timeout + " " + unit.toString());
    TimeoutException timeoutException = new TimeoutException();
    timeoutException.initCause(lastException);
    throw timeoutException;
}
 
Example 7
Source File: SettableFuture.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized T get(long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException
{
  long startTime = System.currentTimeMillis();

  while (!completed && System.currentTimeMillis() - startTime > unit.toMillis(timeout)) {
    wait(unit.toMillis(timeout));
  }

  if (!completed) throw new TimeoutException();
  else            return get();
}
 
Example 8
Source File: RealServerSentEvent.java    From oksse with Apache License 2.0 5 votes vote down vote up
@Override
public void setTimeout(long timeout, TimeUnit unit) {
    if (sseReader != null) {
        sseReader.setTimeout(timeout, unit);
    }
    readTimeoutMillis = unit.toMillis(timeout);
}
 
Example 9
Source File: ForkJoinTask.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
/**
 * Waits if necessary for at most the given time for the computation
 * to complete, and then retrieves its result, if available.
 *
 * @param timeout the maximum time to wait
 * @param unit the time unit of the timeout argument
 * @return the computed result
 * @throws CancellationException if the computation was cancelled
 * @throws ExecutionException if the computation threw an
 * exception
 * @throws InterruptedException if the current thread is not a
 * member of a ForkJoinPool and was interrupted while waiting
 * @throws TimeoutException if the wait timed out
 */
public final V get(long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException {
    Thread t = Thread.currentThread();
    if (t instanceof ForkJoinWorkerThread) {
        ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
        long nanos = unit.toNanos(timeout);
        if (status >= 0) {
            boolean completed = false;
            if (w.unpushTask(this)) {
                try {
                    completed = exec();
                } catch (Throwable rex) {
                    setExceptionalCompletion(rex);
                }
            }
            if (completed)
                setCompletion(NORMAL);
            else if (status >= 0 && nanos > 0)
                w.pool.timedAwaitJoin(this, nanos);
        }
    }
    else {
        long millis = unit.toMillis(timeout);
        if (millis > 0)
            externalInterruptibleAwaitDone(millis);
    }
    int s = status;
    if (s != NORMAL) {
        Throwable ex;
        if (s == CANCELLED)
            throw new CancellationException();
        if (s != EXCEPTIONAL)
            throw new TimeoutException();
        if ((ex = getThrowableException()) != null)
            throw new ExecutionException(ex);
    }
    return getRawResult();
}
 
Example 10
Source File: ListAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Polls the messages list for it to grow to a given minimum size at most timeout timeUnits and return a copy of
 * what we have so far.
 */
public List<String> getMessages(final int minSize, final long timeout, final TimeUnit timeUnit) throws InterruptedException {
    final long endMillis = System.currentTimeMillis() + timeUnit.toMillis(timeout);
    while (messages.size() < minSize && System.currentTimeMillis() < endMillis) {
        Thread.sleep(100);
    }
    return getMessages();
}
 
Example 11
Source File: CachedTask.java    From android-lite-async with Apache License 2.0 5 votes vote down vote up
/**
 * @param context app context
 * @param key identify label, each single cachedtask should not be the same.
 * @param cacheTime expired time
 * @param unit if timeunit is null, see cacheTime as millisecond.
 */
public CachedTask(Context context, String key, long cacheTime, TimeUnit unit) {
	if (context == null) throw new RuntimeException("CachedTask Initialized Must has Context");
	cachePath = context.getFilesDir().getAbsolutePath() + DEFAULT_PATH;
       if (key == null) throw new RuntimeException("CachedTask Must Has Key for Search ");
	this.key = key;
	if (unit != null) expiredTime = unit.toMillis(cacheTime);
	else expiredTime = cacheTime;
}
 
Example 12
Source File: OkHttpClient.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout.
 *
 * @see URLConnection#setConnectTimeout(int)
 */
public void setConnectTimeout(long timeout, TimeUnit unit) {
  if (timeout < 0) {
    throw new IllegalArgumentException("timeout < 0");
  }
  if (unit == null) {
    throw new IllegalArgumentException("unit == null");
  }
  long millis = unit.toMillis(timeout);
  if (millis > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("Timeout too large.");
  }
  connectTimeout = (int) millis;
}
 
Example 13
Source File: DefaultWaiter.java    From webtester2-core with Apache License 2.0 5 votes vote down vote up
@Override
public void waitExactly(long duration, TimeUnit timeUnit) {
    try {
        long millisToSleep = timeUnit.toMillis(duration);
        if (millisToSleep > 0) {
            sleeper.sleep(millisToSleep);
        }
    } catch (InterruptionException e) {
        log.debug("wait was interrupted", e);
    }
}
 
Example 14
Source File: JmsMultipleBrokersTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Timed wait for {@link #hasBridge(String, String)}.
 *
 * @param localBrokerName  - the name of the broker on the "local" side of the bridge
 * @param remoteBrokerName - the name of the broker on the "remote" side of the bridge
 * @param time             - the maximum time to wait for the bridge to be established
 * @param units            - the units for <param>time</param>
 * @throws InterruptedException - if the calling thread is interrupted
 * @throws TimeoutException     - if the bridge is not established within the time limit
 * @throws Exception            - some other unknown error occurs
 * @see #hasBridge(String, String)
 */
protected void waitForBridge(final String localBrokerName,
                             final String remoteBrokerName,
                             long time,
                             TimeUnit units) throws InterruptedException, TimeoutException, Exception {
   if (!Wait.waitFor(new Wait.Condition() {
      @Override
      public boolean isSatisified() {
         return hasBridge(localBrokerName, remoteBrokerName);
      }
   }, units.toMillis(time))) {
      throw new TimeoutException("Bridge not established from broker " + localBrokerName + " to " + remoteBrokerName + " within " + units.toMillis(time) + " milliseconds.");
   }
}
 
Example 15
Source File: SaneSession.java    From jfreesane with Apache License 2.0 5 votes vote down vote up
/**
 * Establishes a connection to the SANE daemon running on the given host on the given port. If the
 * connection cannot be established within the given timeout,
 * {@link java.net.SocketTimeoutException} is thrown.
 *
 * @param saneSocketAddress the socket address of the SANE server
 * @param timeout the timeout for connections to the SANE server, zero implies no connection
 * timeout, must not be greater than {@link Integer#MAX_VALUE} milliseconds.
 * @param timeUnit connection timeout unit
 * @param soTimeout the timeout for reads from the SANE server, zero implies no read timeout
 * @param soTimeUnit socket timeout unit
 * @return a {@code SaneSession} that is connected to the remote SANE server
 * @throws IOException if any error occurs while communicating with the SANE server
 */
public static SaneSession withRemoteSane(
    InetSocketAddress saneSocketAddress,
    long timeout,
    TimeUnit timeUnit,
    long soTimeout,
    TimeUnit soTimeUnit)
    throws IOException {
  long connectTimeoutMillis = timeUnit.toMillis(timeout);
  Preconditions.checkArgument(
      connectTimeoutMillis >= 0 && connectTimeoutMillis <= Integer.MAX_VALUE,
      "Timeout must be between 0 and Integer.MAX_VALUE milliseconds");
  // If the user specifies a non-zero timeout that rounds to 0 milliseconds,
  // set the timeout to 1 millisecond instead.
  if (timeout > 0 && connectTimeoutMillis == 0) {
    Logger.getLogger(SaneSession.class.getName())
        .log(
            Level.WARNING,
            "Specified timeout of {0} {1} rounds to 0ms and was clamped to 1ms",
            new Object[] {timeout, timeUnit});
  }
  Socket socket = new Socket();
  socket.setTcpNoDelay(true);
  long soTimeoutMillis = 0;

  if (soTimeUnit != null && soTimeout > 0) {
    soTimeoutMillis = soTimeUnit.toMillis(soTimeout);
    Preconditions.checkArgument(
        soTimeoutMillis >= 0 && soTimeoutMillis <= Integer.MAX_VALUE,
        "Socket timeout must be between 0 and Integer.MAX_VALUE milliseconds");
    socket.setSoTimeout((int) soTimeoutMillis);
  }
  socket.connect(saneSocketAddress, (int) connectTimeoutMillis);
  SaneSession session =
      new SaneSession(socket, (int) connectTimeoutMillis, (int) soTimeoutMillis);
  session.initSane();
  return session;
}
 
Example 16
Source File: DownInstancePolicy.java    From curator with Apache License 2.0 4 votes vote down vote up
/**
 * @param timeout window of time for down instances
 * @param unit time unit
 * @param errorThreshold number of errors within time window that denotes a down instance
 */
public DownInstancePolicy(long timeout, TimeUnit unit, int errorThreshold)
{
    this.timeoutMs = unit.toMillis(timeout);
    this.errorThreshold = errorThreshold;
}
 
Example 17
Source File: MockExecutorService.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public MockExecutorJob<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
	RepeatingJob<?> job = new RepeatingJob<>(Executors.callable(command), unit.toMillis(initialDelay), unit.toMillis(delay));
	jobs.add(job);
	return job;
}
 
Example 18
Source File: CacheEntry.java    From tinker-manager with Apache License 2.0 4 votes vote down vote up
public CacheEntry(T entry, TimeUnit timeUnit, long duration) {
    this.entry = entry;
    expireMillis = System.currentTimeMillis() + timeUnit.toMillis(duration);
}
 
Example 19
Source File: SpritzStep.java    From spritz with Apache License 2.0 4 votes vote down vote up
public Builder withSwipeDuration(long swipeDuration, TimeUnit timeUnit) {
    this.swipeDuration = timeUnit.toMillis(swipeDuration);
    return this;
}
 
Example 20
Source File: DB.java    From FastBootWeixin with Apache License 2.0 4 votes vote down vote up
/** Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.  */
public HTreeMapMaker expireAfterWrite(long interval, TimeUnit timeUnit){
    this.expire = timeUnit.toMillis(interval);
    return this;
}