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:ch.ivyteam.ivy.maven.engine.deploy.MarkerFileDeployer.java

private static void wait(Supplier<Boolean> condition, long duration, TimeUnit unit) throws TimeoutException {
    long waitMs = unit.toMillis(duration);
    long startMs = System.currentTimeMillis();
    long maxMs = waitMs + startMs;
    while (!condition.get()) {
        try {/* ww  w .  j  a va 2s .c o m*/
            if (System.currentTimeMillis() > maxMs) {
                throw new TimeoutException("Operation reached timeout of " + duration + " " + unit);
            }
            Thread.sleep(100);
        } catch (InterruptedException ex) {
        }
    }
}

From source file:com.bj58.spat.gaea.server.util.async.AsyncWorker.java

private void execNoTimeLimitTask() {
    AsyncTask task = null;//from  w  w  w .j av  a 2s . c o m
    try {
        task = taskQueue.take();
        if (task != null) {
            if ((System.currentTimeMillis() - task.getAddTime()) > task.getQtimeout()) {
                task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                return;
            } else {
                Object obj = task.getHandler().run();
                task.getHandler().messageReceived(obj);
            }
        } else {
            logger.error("execNoTimeLimitTask take task is null");
        }
    } catch (InterruptedException ie) {

    } catch (Throwable ex) {
        if (task != null) {
            task.getHandler().exceptionCaught(ex);
        }
    }
}

From source file:co.cask.tigon.test.SQLFlowTestBase.java

/**
 * This function deploys an instance of the flowClass.
 * Recommended, make this function call from a {@link org.junit.BeforeClass} annotated method.
 * @param flowClass Class of the {@link co.cask.tigon.api.flow.Flow} to be deployed
 * @throws Exception/*  ww  w.  j  a  va 2 s .co m*/
 */
public static void setupFlow(Class<? extends Flow> flowClass) throws Exception {
    Map<String, String> runtimeArgs = Maps.newHashMap();
    handler = new TestHandler();
    service = NettyHttpService.builder().addHttpHandlers(ImmutableList.of(handler))
            .setPort(Networks.getRandomPort()).build();
    service.startAndWait();
    InetSocketAddress address = service.getBindAddress();
    serviceURL = "http://" + address.getHostName() + ":" + address.getPort() + "/queue";
    runtimeArgs.put("baseURL", serviceURL);
    runtimeArgs.put(Constants.HTTP_PORT, Integer.toString(httpPort));
    flowManager = deployFlow(flowClass, runtimeArgs);
    int maxWait = 100;
    // Waiting for the Tigon SQL Flow initialization
    while ((!flowManager.discover(Constants.HTTP_PORT).iterator().hasNext()) && (maxWait > 0)) {
        TimeUnit.SECONDS.sleep(1);
        maxWait = maxWait - 1;
    }
    if (maxWait <= 0) {
        throw new TimeoutException("Timeout Error, Tigon SQL flow took too long to initiate");
    }
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@Test
public void testSetCallbackIsAppliedProperly() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    tempWatcher.setCallback(file -> latch.countDown());
    TempWatcher lastChild = getChildRecursively(tempWatcher);
    Consumer<File> callback = lastChild.getCallback();

    callback.accept(null);//from   w w w  .ja  v a 2  s  . co  m

    if (!latch.await(500, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException("Latch was not tripped.");
    }
}

From source file:org.apache.hadoop.hbase.GenericTestUtils.java

public static void waitFor(Supplier<Boolean> check, int checkEveryMillis, int waitForMillis)
        throws TimeoutException, InterruptedException {
    long st = Time.now();
    do {/*from w  w w . j  a  v  a  2s. co  m*/
        boolean result = check.get();
        if (result) {
            return;
        }

        Thread.sleep(checkEveryMillis);
    } while (Time.now() - st < waitForMillis);

    throw new TimeoutException("Timed out waiting for condition. " + "Thread diagnostics:\n"
            + TimedOutTestsListener.buildThreadDiagnosticString());
}

From source file:org.apache.gobblin.elasticsearch.writer.FutureCallbackHolder.java

public FutureCallbackHolder(final @Nullable WriteCallback callback, ExceptionLogger exceptionLogger,
        final MalformedDocPolicy malformedDocPolicy) {
    this.future = new Future<WriteResponse>() {
        @Override/*www . j  a  v a  2  s  .  c o  m*/
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return done.get();
        }

        @Override
        public WriteResponse get() throws InterruptedException, ExecutionException {
            Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.take();
            return getWriteResponseorThrow(writeResponseThrowablePair);
        }

        @Override
        public WriteResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.poll(timeout, unit);
            if (writeResponseThrowablePair == null) {
                throw new TimeoutException("Timeout exceeded while waiting for future to be done");
            } else {
                return getWriteResponseorThrow(writeResponseThrowablePair);
            }
        }
    };

    this.actionListener = new ActionListener<BulkResponse>() {
        @Override
        public void onResponse(BulkResponse bulkItemResponses) {
            if (bulkItemResponses.hasFailures()) {
                boolean logicalErrors = false;
                boolean serverErrors = false;
                for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
                    if (bulkItemResponse.isFailed()) {
                        // check if the failure is permanent (logical) or transient (server)
                        if (isLogicalError(bulkItemResponse)) {
                            // check error policy
                            switch (malformedDocPolicy) {
                            case IGNORE: {
                                log.debug("Document id {} was malformed with error {}",
                                        bulkItemResponse.getId(), bulkItemResponse.getFailureMessage());
                                break;
                            }
                            case WARN: {
                                log.warn("Document id {} was malformed with error {}", bulkItemResponse.getId(),
                                        bulkItemResponse.getFailureMessage());
                                break;
                            }
                            default: {
                                // Pass through
                            }
                            }
                            logicalErrors = true;
                        } else {
                            serverErrors = true;
                        }
                    }
                }
                if (serverErrors) {
                    onFailure(new RuntimeException(
                            "Partial failures in the batch: " + bulkItemResponses.buildFailureMessage()));
                } else if (logicalErrors) {
                    // all errors found were logical, throw RuntimeException if policy says to Fail
                    switch (malformedDocPolicy) {
                    case FAIL: {
                        onFailure(new RuntimeException(
                                "Partial non-recoverable failures in the batch. To ignore these, set "
                                        + ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_MALFORMED_DOC_POLICY
                                        + " to " + MalformedDocPolicy.IGNORE.name()));
                        break;
                    }
                    default: {
                        WriteResponse writeResponse = new GenericWriteResponse<BulkResponse>(bulkItemResponses);
                        writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                        if (callback != null) {
                            callback.onSuccess(writeResponse);
                        }
                    }
                    }
                }
            } else {
                WriteResponse writeResponse = new GenericWriteResponse<BulkResponse>(bulkItemResponses);
                writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                if (callback != null) {
                    callback.onSuccess(writeResponse);
                }
            }
        }

        private boolean isLogicalError(BulkItemResponse bulkItemResponse) {
            String failureMessage = bulkItemResponse.getFailureMessage();
            return failureMessage.contains("IllegalArgumentException")
                    || failureMessage.contains("illegal_argument_exception")
                    || failureMessage.contains("MapperParsingException")
                    || failureMessage.contains("mapper_parsing_exception");
        }

        @Override
        public void onFailure(Exception exception) {
            writeResponseQueue.add(new Pair<WriteResponse, Throwable>(null, exception));
            if (exceptionLogger != null) {
                exceptionLogger.log(exception);
            }
            if (callback != null) {
                callback.onFailure(exception);
            }
        }
    };
}

From source file:org.pvalsecc.comm.MultiplexedServer.java

/**
 * Start (blocking) the thread and start to listen on the server socket.
 */// w w  w  . j  a va  2  s .co m
public void start(long timeout) throws TimeoutException {
    thread = new Thread(this, threadName);
    thread.start();

    final long maxWait = System.currentTimeMillis() + timeout;

    synchronized (socketCreatedLock) {
        while (!socketCreated) {
            long toWait = maxWait - System.currentTimeMillis();
            if (toWait <= 0) {
                throw new TimeoutException("Could not start the multiplexed server [" + threadName + "].");
            }
            try {
                socketCreatedLock.wait(toWait);
            } catch (InterruptedException ignored) {
                //ignored
            }
        }
    }
}

From source file:com.highcharts.export.converter.SVGConverter.java

public String requestServer(String params)
        throws SVGConverterException, TimeoutException, NoSuchElementException, PoolException {
    Server server = null;/* w w w  .  ja  va 2s.c o  m*/

    try {
        server = (Server) serverPool.borrowObject();
        String response = server.request(params);

        return response;
    } catch (SocketTimeoutException ste) {
        throw new TimeoutException(ste.getMessage());
    } catch (TimeoutException te) {
        throw new TimeoutException(te.getMessage());
    } catch (PoolException nse) {
        logger.error("POOL EXHAUSTED!!");
        throw new PoolException(nse.getMessage());
    } catch (Exception e) {
        logger.debug(e.getMessage());
        throw new SVGConverterException("Error converting SVG" + e.getMessage());
    } finally {
        try {
            serverPool.returnObject(server, true);
        } catch (Exception e) {
            logger.error("Exception while returning server to pool: " + e.getMessage());
        }
    }
}

From source file:org.apache.carbondata.hive.server.HiveEmbeddedServer2.java

private void waitForStartup() throws Exception {
    long timeout = TimeUnit.MINUTES.toMillis(1);
    long unitOfWait = TimeUnit.SECONDS.toMillis(1);

    CLIService hs2Client = getServiceClientInternal();
    SessionHandle sessionHandle = null;/*from  w ww.j  a v  a  2  s .  c  o  m*/
    for (int interval = 0; interval < timeout / unitOfWait; interval++) {
        Thread.sleep(unitOfWait);
        try {
            Map<String, String> sessionConf = new HashMap<String, String>();
            sessionHandle = hs2Client.openSession("foo", "bar", sessionConf);
            return;
        } catch (Exception e) {
            // service not started yet
            continue;
        } finally {
            hs2Client.closeSession(sessionHandle);
        }
    }
    throw new TimeoutException("Couldn't get a hold of HiveServer2...");
}

From source file:com.bj58.spat.gaea.server.util.async.AsyncWorker.java

private void execTimeoutTask() {
    try {//from www .  j ava  2s .  c  om
        final AsyncTask task = taskQueue.take();
        if (task != null) {
            if ((System.currentTimeMillis() - task.getAddTime()) > task.getQtimeout()) {
                task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                return;
            } else {
                final CountDownLatch cdl = new CountDownLatch(1);
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Object obj = task.getHandler().run();
                            task.getHandler().messageReceived(obj);
                        } catch (Throwable ex) {
                            task.getHandler().exceptionCaught(ex);
                        } finally {
                            cdl.countDown();
                        }
                    }
                });
                cdl.await(getTimeout(task.getTimeout(), taskQueue.size()), TimeUnit.MILLISECONDS);
                if (cdl.getCount() > 0) {
                    task.getHandler().exceptionCaught(new TimeoutException("async task timeout!"));
                }
            }
        } else {
            logger.error("execTimeoutTask take task is null");
        }
    } catch (InterruptedException ie) {
        logger.error("");
    } catch (Throwable e) {
        logger.error("get task from poll error", e);
    }
}