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:org.apache.cassandra.service.ReadCallback.java

public T get() throws TimeoutException, DigestMismatchException, IOException {
    long timeout = DatabaseDescriptor.getRpcTimeout() - (System.currentTimeMillis() - startTime);
    boolean success;
    try {/*from   www .  java 2s .  c o  m*/
        success = condition.await(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new AssertionError(ex);
    }

    if (!success) {
        StringBuilder sb = new StringBuilder("");
        for (Message message : resolver.getMessages())
            sb.append(message.getFrom()).append(", ");
        throw new TimeoutException("Operation timed out - received only " + received.get() + " responses from "
                + sb.toString() + " .");
    }

    return blockfor == 1 ? resolver.getData() : resolver.resolve();
}

From source file:org.apache.tinkerpop.gremlin.server.handler.IteratorHandler.java

@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {
    if (msg instanceof Pair) {
        try {//from  w  w  w .  ja  va2s. c om
            final Pair pair = (Pair) msg;
            final Iterator itty = (Iterator) pair.getValue1();
            final RequestMessage requestMessage = (RequestMessage) pair.getValue0();

            // the batch size can be overriden by the request
            final int resultIterationBatchSize = (Integer) requestMessage.optionalArgs(Tokens.ARGS_BATCH_SIZE)
                    .orElse(settings.resultIterationBatchSize);

            // timer for the total serialization time
            final StopWatch stopWatch = new StopWatch();

            final EventExecutorGroup executorService = ctx.executor();
            final Future<?> iteration = executorService.submit((Callable<Void>) () -> {
                logger.debug("Preparing to iterate results from - {} - in thread [{}]", requestMessage,
                        Thread.currentThread().getName());

                stopWatch.start();

                List<Object> aggregate = new ArrayList<>(resultIterationBatchSize);
                while (itty.hasNext()) {
                    aggregate.add(itty.next());

                    // send back a page of results if batch size is met or if it's the end of the results being
                    // iterated
                    if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) {
                        final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT
                                : ResponseStatusCode.SUCCESS;
                        ctx.writeAndFlush(
                                ResponseMessage.build(requestMessage).code(code).result(aggregate).create());
                        aggregate = new ArrayList<>(resultIterationBatchSize);
                    }

                    stopWatch.split();
                    if (stopWatch.getSplitTime() > settings.serializedResponseTimeout)
                        throw new TimeoutException(
                                "Serialization of the entire response exceeded the serializeResponseTimeout setting");

                    stopWatch.unsplit();
                }

                return null;
            });

            iteration.addListener(f -> {
                stopWatch.stop();

                if (!f.isSuccess()) {
                    final String errorMessage = String.format(
                            "Response iteration and serialization exceeded the configured threshold for request [%s] - %s",
                            msg, f.cause().getMessage());
                    logger.warn(errorMessage);
                    ctx.writeAndFlush(
                            ResponseMessage.build(requestMessage).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                                    .statusMessage(errorMessage).create());
                }
            });
        } finally {
            ReferenceCountUtil.release(msg);
        }

    } else {
        ctx.write(msg, promise);
    }
}

From source file:org.openbaton.common.vnfm_sdk.amqp.VnfmSpringHelperRabbit.java

@Override
public String sendAndReceive(String message, String queueName) throws Exception {

    rabbitTemplate.setReplyTimeout(timeout * 1000);
    rabbitTemplate.afterPropertiesSet();

    log.debug("Sending to: " + queueName);
    String res = (String) rabbitTemplate.convertSendAndReceive("openbaton-exchange", queueName, message);
    log.trace("Received from EMS: " + res);
    if (res == null) {
        log.error("After " + timeout + " seconds the ems did not answer.");
        throw new TimeoutException("After " + timeout
                + " seconds the ems did not answer. You can change this value by editing the application.properties propery \"vnfm.rabbitmq.sar.timeout\"");
    }//  ww  w  .j  av  a2 s  .c  o m
    return res;
}

From source file:no.ntnu.osnap.com.Protocol.java

/**
 * //from   w  w  w .  j  a v  a2s.c  om
 * @throws TimeoutException
 */
protected void handshakeConnection() throws TimeoutException {
    ProtocolInstruction newInstruction = new ProtocolInstruction(OpCode.DEVICE_INFO, (byte) 0, new byte[1]);

    // Blocking method lock();
    lock();
    try {
        waitingForAck = OpCode.DEVICE_INFO;
        tempAckProcessor = OpCode.DEVICE_INFO;
        sendBytes(newInstruction.getInstructionBytes());
    } catch (IOException ex) {
        throw new TimeoutException("Failed to send metadata request: " + ex);
    }
    release();

    //Wait until we get a response or a timeout
    long timeout = System.currentTimeMillis() + TIMEOUT;
    while (waitingForAck != null) {

        //Timeout?
        if (System.currentTimeMillis() > timeout)
            throw new TimeoutException("handshakeConnection() has timed out (did not recieve all data)");

        //Wait 10 ms for a resonse
        try {
            Thread.sleep(10);
        } catch (InterruptedException ex) {
        }
    }

    //Build a string from the byte array
    String response = new String(currentCommand.getContent());

    //Finished processing this instruction
    tempAckProcessor = null;
    ackProcessingComplete();

    //Build a MetaData package out from the raw String object using JSON parsing
    try {
        connectionMetadata = new ConnectionMetadata(new JSONObject(response));
    } catch (JSONException e) {
        throw new TimeoutException("JSONException when constructing metadata: " + e);
    }
}

From source file:com.galenframework.suite.actions.GalenPageActionWait.java

@Override
public void execute(TestReport report, Browser browser, GalenPageTest pageTest,
        ValidationListener validationListener) throws Exception {
    Page page = browser.getPage();//  w  w  w. j a  va 2  s . c o m

    if (untilElements == null || untilElements.isEmpty()) {
        Thread.sleep(timeout);
    } else {
        // waiting for elements
        int period = 500;
        int tries = timeout / period;
        while (tries-- > 0) {
            Thread.sleep(period);
            if (checkAllConditions(page, null)) {
                return;
            }
        }

        StringBuffer results = new StringBuffer();
        if (!checkAllConditions(page, results)) {
            throw new TimeoutException("Failed waiting for:\n" + results.toString());
        }
    }
}

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."));
                    }/*www .ja  va  2s.  com*/
                }

                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:org.apache.hadoop.hdfs.server.balancer.TestBalancerWithNodeGroup.java

/**
 * Wait until heartbeat gives expected results, within CAPACITY_ALLOWED_VARIANCE, 
 * summed over all nodes.  Times out after TIMEOUT msec.
 * @param expectedUsedSpace/*from   w  w  w.  j a va2 s.co  m*/
 * @param expectedTotalSpace
 * @throws IOException - if getStats() fails
 * @throws TimeoutException
 */
private void waitForHeartBeat(long expectedUsedSpace, long expectedTotalSpace)
        throws IOException, TimeoutException {
    long timeout = TIMEOUT;
    long failtime = (timeout <= 0L) ? Long.MAX_VALUE : System.currentTimeMillis() + timeout;

    while (true) {
        long[] status = client.getStats();
        double totalSpaceVariance = Math.abs((double) status[0] - expectedTotalSpace) / expectedTotalSpace;
        double usedSpaceVariance = Math.abs((double) status[1] - expectedUsedSpace) / expectedUsedSpace;
        if (totalSpaceVariance < CAPACITY_ALLOWED_VARIANCE && usedSpaceVariance < CAPACITY_ALLOWED_VARIANCE)
            break; //done

        if (System.currentTimeMillis() > failtime) {
            throw new TimeoutException("Cluster failed to reached expected values of " + "totalSpace (current: "
                    + status[0] + ", expected: " + expectedTotalSpace + "), or usedSpace (current: " + status[1]
                    + ", expected: " + expectedUsedSpace + "), in more than " + timeout + " msec.");
        }
        try {
            Thread.sleep(100L);
        } catch (InterruptedException ignored) {
        }
    }
}

From source file:org.apache.sentry.tests.e2e.kafka.AbstractKafkaSentryTestBase.java

public static void startSentryServer() throws Exception {
    sentryServer.start();//from   www .  j a v  a2 s  .  c o  m
    final long start = System.currentTimeMillis();
    while (!sentryServer.isRunning()) {
        Thread.sleep(1000);
        if (System.currentTimeMillis() - start > 60000L) {
            throw new TimeoutException("Server did not start after 60 seconds");
        }
    }
}

From source file:org.apache.sentry.tests.e2e.dbprovider.AbstractTestWithDbProvider.java

private static void startSentryService() throws Exception {
    for (SentryService server : servers) {
        server.start();//  ww w . j a v a  2  s  .co  m
        final long start = System.currentTimeMillis();
        while (!server.isRunning()) {
            Thread.sleep(1000);
            if (System.currentTimeMillis() - start > 60000L) {
                throw new TimeoutException("Server did not start after 60 seconds");
            }
        }
    }
}

From source file:org.cloudifysource.dsl.context.utils.VolumeUtils.java

private static void executeCommandLine(final String commandLine, final long timeout)
        throws LocalStorageOperationException, TimeoutException {

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);//from w  ww.j a  va 2s  .com
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    ProcessOutputStream outAndErr = new ProcessOutputStream();
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outAndErr);
        executor.setStreamHandler(streamHandler);
        logger.info("Executing commandLine : '" + commandLine + "'");
        executor.execute(CommandLine.parse(commandLine));
        logger.info("Execution completed successfully. Process output was : " + outAndErr.getOutput());
    } catch (final Exception e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Timed out while executing commandLine : '" + commandLine + "'");
        }
        throw new LocalStorageOperationException("Failed executing commandLine : '" + commandLine
                + ". Process output was : " + outAndErr.getOutput(), e);
    }
}