Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

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

Prototype

public TimeoutException(String message) 

Source Link

Document

Constructs a TimeoutException with the specified detail message.

Usage

From source file:Main.java

/**
 * Properly shutdown and await pool termination for an arbitrary
 * amount of time./*from  ww w.java  2s.c o m*/
 *
 * @param pool        Pool to shutdown
 * @param waitSeconds Seconds to wait before throwing exception
 * @throws java.util.concurrent.TimeoutException Thrown if the pool does not shutdown in the specified time
 */
public static void shutdownAndWaitForTermination(ExecutorService pool, int waitSeconds)
        throws TimeoutException {
    // shut it down
    pool.shutdown();
    try {
        // wait, wait, wait
        if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
            // things still running, nuke it
            pool.shutdownNow();
            // wait, wait, wai
            if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
                // boo hiss, didn't shutdown
                throw new TimeoutException("Pool did not terminate");
            }
        }
    } catch (InterruptedException ie) {
        // try, try again
        pool.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.jclouds.ProvisioningUtils.java

public static long millisUntil(String errorMessage, long end) throws TimeoutException {
    long millisUntilEnd = end - System.currentTimeMillis();
    if (millisUntilEnd < 0) {
        throw new TimeoutException(errorMessage);
    }//from  w  w w .j av a  2s .c o m
    return millisUntilEnd;
}

From source file:org.blocks4j.reconf.infra.http.layer.SimpleHttpClient.java

private static SimpleHttpResponse execute(CloseableHttpClient httpClient, SimpleHttpRequest request,
        long timeout, TimeUnit timeunit) throws Exception {

    RequestTask task = new RequestTask(httpClient, request);
    Future<SimpleHttpResponse> futureResponse = null;

    try {//from w ww  . j  av  a  2  s . c  o  m
        futureResponse = requestExecutor.submit(task);
        return futureResponse.get(timeout, timeunit);

    } catch (TimeoutException e) {
        httpClient.close();
        RequestLine line = request.getRequestLine();
        String method = request.getMethod();

        if (line != null && method != null) {
            throw new TimeoutException(msg.format("error.complete", method.toUpperCase(), line.getUri(),
                    timeout, timeunit.toString().toLowerCase()));

        } else {
            throw new TimeoutException(msg.format("error", timeout, timeunit.toString().toLowerCase()));
        }

    } catch (Exception e) {
        httpClient.close();
        throw e;

    } finally {
        if (futureResponse != null) {
            futureResponse.cancel(true);
        }
    }
}

From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java

public void readMessages(IChannelSelectorRegistrar channelSelectorRegistrar, Consumer<List<String>> callback,
        Consumer<Exception> exceptionHandler) {
    try {//from  www  . j av a  2  s .  c  o  m
        channelSelectorRegistrar.register(SelectionKey.OP_READ,
                (selectionKey -> read(selectionKey, callback, exceptionHandler)),
                (selectionKey, ops) -> exceptionHandler.accept(new TimeoutException("read timed out")));
    } catch (Exception e) {
        exceptionHandler.accept(e);
    }
}

From source file:com.byteatebit.nbserver.simple.udp.UdpDatagramChannelHandler.java

@Override
public SelectionKey accept(INbContext nbContext, DatagramChannel datagramChannel) {
    IDatagramMessageHandler messageHandler = datagramMessageHandlerFactory.create(nbContext, datagramChannel);
    ReadDatagramTask readDatagramTask = ReadDatagramTask.Builder.builder().withNbContext(nbContext)
            .withDatagramChannel(datagramChannel).withBufferSize(maxDatagramReceiveSize).build();
    Consumer<Exception> exceptionHandler = (e) -> {
        LOG.error("Message read failed.  Closing datagramChannel");
        IOUtils.closeQuietly(datagramChannel);
    };/*w ww .ja  v a 2s .c om*/
    return nbContext.register(datagramChannel, SelectionKey.OP_READ,
            selectionKey -> readDatagramTask.readMessage(selectionKey, messageHandler::accept,
                    exceptionHandler),
            (selectionKey, ops) -> exceptionHandler.accept(new TimeoutException("write timed out")), -1);
}

From source file:com.facebook.infrastructure.service.QuorumResponseHandler.java

public T get() throws TimeoutException, DigestMismatchException, InterruptedException {
    long startTime = System.currentTimeMillis();
    lock_.lock();//w  w  w  .  j  a  v  a 2 s.  c  o m
    try {
        boolean bVal = true;
        if (!done_.get()) {
            bVal = condition_.await(DatabaseDescriptor.getRpcTimeout(), TimeUnit.MILLISECONDS);
        }

        if (!bVal && !done_.get()) {
            throw new TimeoutException("Operation timed out - received only " + responses_.size()
                    + " responses from [" + StringUtils.join(responders(), ", ") + "]");
        }
    } finally {
        lock_.unlock();
        for (Message response : responses_) {
            MessagingService.removeRegisteredCallback(response.getMessageId());
        }
    }
    logger_.debug("QuorumResponseHandler: " + (System.currentTimeMillis() - startTime) + " ms; "
            + " responses from [" + StringUtils.join(responders(), ", ") + "]");

    return responseResolver_.resolve(responses_);
}

From source file:org.cloudifysource.esc.installer.filetransfer.VfsFileTransfer.java

/******
 * Checks if the specified end time has reached.
 *
 * @param endTimeMillis//from w w  w. j a v a2s.c  o  m
 *            the end time.
 * @throws TimeoutException
 *             if the target time has passed.
 */
protected void checkTimeout(final long endTimeMillis) throws TimeoutException {
    if (System.currentTimeMillis() > endTimeMillis) {
        throw new TimeoutException("File transfer operation exceeded timeout");
    }
}

From source file:com.garethahealy.karaf.commands.ensemble.healthy.EnsembleHealthyAction.java

@Override
protected Object doExecute() throws Exception {
    if (tick <= 0) {
        tick = TimeUnit.SECONDS.toMillis(5);
    }//w  w  w.  ja  v  a2 s.com

    if (wait <= 0) {
        wait = TimeUnit.MINUTES.toMillis(1);
    }

    //Sort them to be alphabetical
    Collections.sort(containers);

    log.trace("Checking ensemble of {} for {} every {}ms until {}ms.", StringUtils.join(containers, ','), tick,
            wait);

    Boolean hasTimedOut = waitForEnsembleHealthy();
    if (hasTimedOut) {
        throw new TimeoutException("Took longer than wait value");
    }

    return null;
}

From source file:org.opendaylight.controller.cluster.raft.GetSnapshotReplyActor.java

@Override
public void onReceive(Object message) {
    if (message instanceof CaptureSnapshotReply) {
        Snapshot snapshot = Snapshot.create(((CaptureSnapshotReply) message).getSnapshot(),
                params.captureSnapshot.getUnAppliedEntries(), params.captureSnapshot.getLastIndex(),
                params.captureSnapshot.getLastTerm(), params.captureSnapshot.getLastAppliedIndex(),
                params.captureSnapshot.getLastAppliedTerm(), params.electionTerm.getCurrentTerm(),
                params.electionTerm.getVotedFor(), params.peerInformation);

        LOG.debug("{}: Received CaptureSnapshotReply, sending {}", params.id, snapshot);

        params.replyToActor.tell(new GetSnapshotReply(params.id, SerializationUtils.serialize(snapshot)),
                getSelf());/*www  .  jav  a2 s  .  c  o m*/
        getSelf().tell(PoisonPill.getInstance(), getSelf());
    } else if (message instanceof ReceiveTimeout) {
        LOG.warn("{}: Got ReceiveTimeout for inactivity - did not receive CaptureSnapshotReply within {} ms",
                params.id, params.receiveTimeout.toMillis());

        params.replyToActor.tell(new akka.actor.Status.Failure(new TimeoutException(
                String.format("Timed out after %d ms while waiting for CaptureSnapshotReply",
                        params.receiveTimeout.toMillis()))),
                getSelf());
        getSelf().tell(PoisonPill.getInstance(), getSelf());
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestDeadDatanode.java

/**
 * wait for datanode to reach alive or dead state for waitTime given in
 * milliseconds.//w  ww  .  j av  a  2 s. c om
 */
private void waitForDatanodeState(DatanodeID nodeID, boolean alive, int waitTime)
        throws TimeoutException, InterruptedException, IOException {
    long stopTime = System.currentTimeMillis() + waitTime;
    FSNamesystem namesystem = cluster.getNameNode().getNamesystem();
    String state = alive ? "alive" : "dead";
    while (System.currentTimeMillis() < stopTime) {
        if (namesystem.getDatanode(nodeID).isAlive == alive) {
            LOG.info("datanode " + nodeID + " is " + state);
            return;
        }
        LOG.info("Waiting for datanode " + nodeID + " to become " + state);
        Thread.sleep(1000);
    }
    throw new TimeoutException("Timedout waiting for datanode reach state " + state);
}