Example usage for java.util.concurrent TimeUnit toMillis

List of usage examples for java.util.concurrent TimeUnit toMillis

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit toMillis.

Prototype

public long toMillis(long duration) 

Source Link

Document

Equivalent to #convert(long,TimeUnit) MILLISECONDS.convert(duration, this) .

Usage

From source file:com.taobao.metamorphosis.gregor.slave.OrderedThreadPoolExecutor.java

/**
 * {@inheritDoc}//ww w.j av  a  2  s . c  om
 */
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {

    final long deadline = System.currentTimeMillis() + unit.toMillis(timeout);

    synchronized (this.workers) {
        while (!this.isTerminated()) {
            final long waitTime = deadline - System.currentTimeMillis();
            if (waitTime <= 0) {
                break;
            }

            this.workers.wait(waitTime);
        }
    }
    return this.isTerminated();
}

From source file:com.github.parisoft.resty.client.Client.java

/**
 * Sets the request execution timeout.<br>
 * Under the hood this is done with these {@link HttpClient} configurations:
 * <ul>/*  w  ww .j a  v a 2s .  c o  m*/
 * <li>{@link SocketConfig#getSoTimeout()}</li>
 * <li>{@link RequestConfig#getConnectionRequestTimeout()}</li>
 * <li>{@link RequestConfig#getConnectTimeout()}</li>
 * <li>{@link RequestConfig#getSocketTimeout()}</li>
 * </ul>
 * Default is 0 (no timeout)
 *
 * @param value The timeout value
 * @param unit The timeout unit
 * @return this client
 */
public Client timeout(int value, TimeUnit unit) {
    timeout = (int) unit.toMillis(value);

    return this;
}

From source file:org.apache.nifi.controller.AbstractComponentNode.java

@Override
public ValidationStatus getValidationStatus(long timeout, TimeUnit timeUnit) {
    long millis = timeUnit.toMillis(timeout);
    final long maxTime = System.currentTimeMillis() + millis;

    synchronized (validationState) {
        while (getValidationStatus() == ValidationStatus.VALIDATING) {
            try {
                final long waitMillis = Math.max(0, maxTime - System.currentTimeMillis());
                if (waitMillis <= 0) {
                    break;
                }//  ww  w .j a  v a2  s . c  o  m

                validationState.wait(waitMillis);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return getValidationStatus();
            }
        }

        return getValidationStatus();
    }
}

From source file:com.alibaba.napoli.gecko.service.timer.HashedWheelTimer.java

public Timeout newTimeout(final TimerTask task, long delay, final TimeUnit unit) {
    final long currentTime = System.currentTimeMillis();

    if (task == null) {
        throw new NullPointerException("task");
    }//w  ww . ja  v a 2s  .c o m
    if (unit == null) {
        throw new NullPointerException("unit");
    }

    delay = unit.toMillis(delay);
    if (delay < this.tickDuration) {
        delay = this.tickDuration;
    }

    if (!this.workerThread.isAlive()) {
        this.start();
    }

    if (this.size.get() >= this.maxTimerCapacity) {
        throw new RejectedExecutionException(
                "Timer size " + this.size + " is great than maxTimerCapacity " + this.maxTimerCapacity);
    }

    // Prepare the required parameters to create the timeout object.
    HashedWheelTimeout timeout;
    final long lastRoundDelay = delay % this.roundDuration;
    final long lastTickDelay = delay % this.tickDuration;

    final long relativeIndex = lastRoundDelay / this.tickDuration + (lastTickDelay != 0 ? 1 : 0);

    final long deadline = currentTime + delay;

    final long remainingRounds = delay / this.roundDuration - (delay % this.roundDuration == 0 ? 1 : 0);

    // Add the timeout to the wheel.
    this.lock.readLock().lock();
    try {
        timeout = new HashedWheelTimeout(task, deadline, (int) (this.wheelCursor + relativeIndex & this.mask),
                remainingRounds);

        this.wheel[timeout.stopIndex].add(timeout);
    } finally {
        this.lock.readLock().unlock();
    }
    this.size.incrementAndGet();

    return timeout;
}

From source file:hd3gtv.mydmam.manager.JobNG.java

public JobNG setMaxExecutionTime(long duration, TimeUnit unit) {
    this.max_execution_time = unit.toMillis(duration);
    return this;
}

From source file:org.cloudifysource.esc.driver.provisioning.byon.ByonProvisioningDriver.java

@Override
public MachineDetails startMachine(final String locationId, final long timeout, final TimeUnit timeUnit)
        throws TimeoutException, CloudProvisioningException {

    final long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);

    logger.info(this.getClass().getName() + ": startMachine, management mode: " + management);

    final Set<String> activeMachinesIPs = admin.getMachines().getHostsByAddress().keySet();
    deployer.setAllocated(cloudTemplateName, activeMachinesIPs);
    if (logger.isLoggable(Level.INFO)) {
        logger.info("Verifying the active machines are not in the free pool: "
                + "\n Admin reports the currently used machines are: "
                + Arrays.toString(activeMachinesIPs.toArray())
                + "\n Byon deployer reports the free machines for template " + cloudTemplateName + " are: "
                + Arrays.toString(deployer.getFreeNodesByTemplateName(cloudTemplateName).toArray())
                + "\n Byon deployer reports the currently used machines for template " + cloudTemplateName
                + " are:"
                + Arrays.toString(deployer.getAllocatedNodesByTemplateName(cloudTemplateName).toArray())
                + "\n Byon deployer reports the invalid used machines for template " + cloudTemplateName
                + " are: "
                + Arrays.toString(deployer.getInvalidNodesByTemplateName(cloudTemplateName).toArray()) + ")");
    }//w ww . j  a  va2s.  c  o  m
    final String newServerName = createNewServerName();
    logger.info("Attempting to start a new cloud machine");
    final ComputeTemplate template = this.cloud.getCloudCompute().getTemplates().get(cloudTemplateName);

    return createServer(newServerName, endTime, template);
}

From source file:org.mule.tck.AbstractMuleTestCase.java

public void handleTimeout(long timeout, TimeUnit unit) {
    String msg = "Timeout of " + unit.toMillis(timeout) + "ms exceeded (modify via -Dmule.test.timeoutSecs=XX)";

    if (failOnTimeout) {
        logger.fatal(msg + " - Attempting to interrupt thread for test " + this.getName());
        if (currentTestRunningThread != null) {
            currentTestRunningThread.interrupt();
        }//from  w  ww. j  av  a 2s.  co  m
        giveTheTestSomeTimeToCleanUpAndThenKillIt("Interrupting didn't work. Killing the VM!. Test "
                + this.getName() + " did not finish correctly.");
    } else {
        logger.warn(msg);
    }
}

From source file:org.apache.http.HC4.impl.conn.PoolingHttpClientConnectionManager.java

@Override
public void releaseConnection(final HttpClientConnection managedConn, final Object state, final long keepalive,
        final TimeUnit tunit) {
    Args.notNull(managedConn, "Managed connection");
    synchronized (managedConn) {
        final CPoolEntry entry = CPoolProxy.detach(managedConn);
        if (entry == null) {
            return;
        }/*w  w  w.ja v  a2s . c  o m*/
        final ManagedHttpClientConnection conn = entry.getConnection();
        try {
            if (conn.isOpen()) {
                final TimeUnit effectiveUnit = tunit != null ? tunit : TimeUnit.MILLISECONDS;
                entry.setState(state);
                entry.updateExpiry(keepalive, effectiveUnit);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (keepalive > 0) {
                        s = "for " + (double) effectiveUnit.toMillis(keepalive) / 1000 + " seconds";
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection " + format(entry) + " can be kept alive " + s);
                }
            }
        } finally {
            this.pool.release(entry, conn.isOpen() && entry.isRouteComplete());
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute()));
            }
        }
    }
}

From source file:org.sfs.nodes.RemoteMasterNode.java

@Override
public Observable<Void> stopJob(String jobId, long timeout, TimeUnit timeUnit) {
    return Defer.aVoid().flatMap(aVoid -> nodes.connectFirstAvailable(vertx, hostAndPorts, hostAndPort -> {
        ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();

        String url = String.format("http://%s/_internal_node_master_stop_job/", hostAndPort.toString());

        HttpClientRequest httpClientRequest = httpClient.postAbs(url, httpClientResponse -> {
            httpClientResponse.pause();/*  ww w.ja va2 s .c om*/
            handler.complete(httpClientResponse);
        }).exceptionHandler(handler::fail).putHeader(X_SFS_REMOTE_NODE_TOKEN, remoteNodeSecret)
                .putHeader(JOB_ID, jobId)
                .putHeader(HttpHeaders.TIMEOUT, String.valueOf(timeUnit.toMillis(timeout)))
                .setTimeout(responseTimeout);

        httpClientRequest.end();

        return handler.map(
                httpClientResponse -> new HttpClientRequestAndResponse(httpClientRequest, httpClientResponse));
    })).map(HttpClientRequestAndResponse::getResponse).map(new HttpClientResponseHeaderLogger())
            .flatMap(httpClientResponse -> Defer.just(httpClientResponse)
                    .flatMap(new HttpClientKeepAliveResponseBodyBuffer()).map(new HttpBodyLogger())
                    .map(buffer -> {
                        if (HTTP_OK != httpClientResponse.statusCode()) {
                            throw new HttpClientResponseException(httpClientResponse, buffer);
                        }
                        return buffer;
                    }).map(new BufferToJsonObject()).map(jsonObject -> {
                        Integer code = jsonObject.getInteger("code");
                        if (code != null) {
                            if (HTTP_OK == code) {
                                return jsonObject;
                            } else if (HTTP_CONFLICT == code) {
                                return new Jobs.WaitStoppedExpired();
                            } else if (HTTP_NOT_FOUND == code) {
                                throw new Jobs.JobNotFound();
                            }
                        }
                        throw new HttpClientResponseException(httpClientResponse, jsonObject);
                    }))
            .map(new ToVoid<>());
}

From source file:org.sfs.nodes.RemoteMasterNode.java

@Override
public Observable<Void> executeJob(String jobId, MultiMap params, long timeout, TimeUnit timeUnit) {
    return Defer.aVoid().flatMap(aVoid -> nodes.connectFirstAvailable(vertx, hostAndPorts, hostAndPort -> {
        ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();

        String url = String.format("http://%s/_internal_node_master_execute_job/", hostAndPort.toString());

        HttpClientRequest httpClientRequest = httpClient.postAbs(url, httpClientResponse -> {
            httpClientResponse.pause();//w w  w . j a v  a  2s  .  c om
            handler.complete(httpClientResponse);
        }).exceptionHandler(handler::fail).putHeader(X_SFS_REMOTE_NODE_TOKEN, remoteNodeSecret)
                .putHeader(JOB_ID, jobId)
                .putHeader(HttpHeaders.TIMEOUT, String.valueOf(timeUnit.toMillis(timeout)))
                .setTimeout(responseTimeout);
        httpClientRequest.headers().addAll(params);

        httpClientRequest.end();

        return handler.map(
                httpClientResponse -> new HttpClientRequestAndResponse(httpClientRequest, httpClientResponse));
    })).map(HttpClientRequestAndResponse::getResponse).map(new HttpClientResponseHeaderLogger())
            .flatMap(httpClientResponse -> Defer.just(httpClientResponse)
                    .flatMap(new HttpClientKeepAliveResponseBodyBuffer()).map(new HttpBodyLogger())
                    .map(buffer -> {
                        if (HTTP_OK != httpClientResponse.statusCode()) {
                            throw new HttpClientResponseException(httpClientResponse, buffer);
                        }
                        return buffer;
                    }).map(new BufferToJsonObject()).map(jsonObject -> {
                        Integer code = jsonObject.getInteger("code");
                        if (code != null) {
                            if (HTTP_OK == code) {
                                return jsonObject;
                            } else if (HTTP_CONFLICT == code) {
                                return new Jobs.JobAlreadyRunning();
                            } else if (HTTP_NOT_FOUND == code) {
                                throw new Jobs.JobNotFound();
                            }
                        }
                        throw new HttpClientResponseException(httpClientResponse, jsonObject);
                    }))
            .map(new ToVoid<>());
}