Example usage for com.google.common.util.concurrent TimeLimiter callWithTimeout

List of usage examples for com.google.common.util.concurrent TimeLimiter callWithTimeout

Introduction

In this page you can find the example usage for com.google.common.util.concurrent TimeLimiter callWithTimeout.

Prototype

<T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean interruptible)
        throws Exception;

Source Link

Document

Invokes a specified Callable, timing out after the specified time limit.

Usage

From source file:com.facebook.presto.ml.AbstractSvmModel.java

@Override
public void train(Dataset dataset) {
    params.svm_type = getLibsvmType();//  w w  w  .  j  a  v a2  s .com

    svm_problem problem = toSvmProblem(dataset);

    ExecutorService service = newCachedThreadPool(
            threadsNamed("libsvm-trainer-" + System.identityHashCode(this) + "-%s"));
    try {
        TimeLimiter limiter = new SimpleTimeLimiter(service);
        //TODO: this time limit should be configurable
        model = limiter.callWithTimeout(getTrainingFunction(problem, params), 1, TimeUnit.HOURS, true);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw Throwables.propagate(e);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    } finally {
        service.shutdownNow();
    }
}

From source file:me.defying.chili.timeout.TimeoutInterceptor.java

@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    // get annotation, class, method and arguments
    Timeout annotation = InvocationUtils.getAnnotation(invocation, Timeout.class);

    // do nothing
    if (annotation.time() <= 0) {
        return invocation.proceed();
    }//from  ww  w . j  av  a2s . com

    TimeLimiter limiter = new SimpleTimeLimiter();

    // underlying method invoker
    Callable<Object> invoker = new TimeoutInvoker(invocation);

    try {
        return limiter.callWithTimeout(invoker, annotation.time(), annotation.unit(), true);
    } catch (UncheckedTimeoutException ex) {
        throw new TimeoutException(ex);
    } catch (ChiliException ex) {
        // when the underlying method invokation throws an exception we need
        // to unrap it in order to existing code get the real exception
        throw ex.getCause();
    }
}

From source file:com.eucalyptus.cloud.ws.TCPHandler.java

public void run() {
    try (final Socket socket = this.socket) {
        socket.setSoTimeout(timeout_seconds * 1000);
        final TimeLimiter limiter = new SimpleTimeLimiter(Threads.lookup(Dns.class, TCPHandler.class));
        final byte[] inBytes = limiter.callWithTimeout(new Callable<byte[]>() {
            @Override//from w ww.j a  va  2 s. co m
            public byte[] call() throws Exception {
                final DataInputStream inStream = new DataInputStream(socket.getInputStream());
                final int inputLength = inStream.readUnsignedShort();
                byte[] inBytes = new byte[inputLength];
                inStream.readFully(inBytes);
                return inBytes;
            }
        }, timeout_seconds, TimeUnit.SECONDS, false);

        byte[] response = null;
        try {
            final Message query = new Message(inBytes);
            ConnectionHandler.setLocalAndRemoteInetAddresses(socket.getLocalAddress(), socket.getInetAddress());
            try {
                response = generateReply(query, inBytes, inBytes.length, socket);
            } catch (RuntimeException ex) {
                response = errorMessage(query, Rcode.SERVFAIL);
                throw ex;
            } finally {
                ConnectionHandler.clearInetAddresses();
            }
            if (response == null)
                return;
        } catch (IOException exception) {
            LOG.error(exception);
        }
        final DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
        outStream.writeShort(response.length);
        outStream.write(response);
        outStream.flush();
    } catch (UncheckedTimeoutException e) {
        LOG.debug("Timeout reading request.");
    } catch (Exception ex) {
        LOG.error(ex);
    }
}

From source file:org.bin01.db.verifier.Validator.java

private QueryResult executeQuery(String url, String username, String password, Query query, Duration timeout) {
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        connection.setClientInfo("ApplicationName", "verifier-test:" + queryPair.getName());
        connection.setCatalog(query.getCatalog());
        connection.setSchema(query.getSchema());
        long start = System.nanoTime();

        try (Statement statement = connection.createStatement()) {
            TimeLimiter limiter = new SimpleTimeLimiter();
            Stopwatch stopwatch = Stopwatch.createStarted();
            Statement limitedStatement = limiter.newProxy(statement, Statement.class, timeout.toMillis(),
                    TimeUnit.MILLISECONDS);
            try (final ResultSet resultSet = limitedStatement.executeQuery(query.getQuery())) {
                List<List<Object>> results = limiter.callWithTimeout(getResultSetConverter(resultSet),
                        timeout.toMillis() - stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS,
                        true);//  www  .  ja  va  2s  .  c om
                return new QueryResult(State.SUCCESS, null, nanosSince(start), results);
            } catch (AssertionError e) {
                if (e.getMessage().startsWith("unimplemented type:")) {
                    return new QueryResult(State.INVALID, null, null, ImmutableList.<List<Object>>of());
                }
                throw e;
            } catch (SQLException | VerifierException e) {
                throw e;
            } catch (UncheckedTimeoutException e) {
                return new QueryResult(State.TIMEOUT, null, null, ImmutableList.<List<Object>>of());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw Throwables.propagate(e);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    } catch (SQLException e) {
        Exception exception = e;
        if (("Error executing query".equals(e.getMessage()) || "Error fetching results".equals(e.getMessage()))
                && (e.getCause() instanceof Exception)) {
            exception = (Exception) e.getCause();
        }
        State state = State.FAILED;
        return new QueryResult(state, exception, null, null);
    } catch (VerifierException e) {
        return new QueryResult(State.TOO_MANY_ROWS, e, null, null);
    }
}

From source file:org.zenoss.zep.index.impl.lucene.LuceneEventIndexBackend.java

private TopDocs timeLimitedSearch(final IndexSearcher searcher, final Query query, final Sort sort,
        final int offset, final int limit, final int numDocs) throws ZepException {

    TopDocs docs;//w  w  w  .  j a  v a2 s .c  om

    Callable search_call = new Callable<TopDocs>() {
        public TopDocs call() throws IOException, Exception {
            TopDocs tdocs;
            if (sort != null) {
                logger.debug("Query: {}, Sort: {}, Offset: {}, Limit: {}",
                        new Object[] { query, sort, offset, limit });
                tdocs = searcher.search(query, null, numDocs, sort);
            } else {
                logger.debug("Query: {}, Offset: {}, Limit: {}", new Object[] { query, offset, limit });
                tdocs = searcher.search(query, null, numDocs);
            }
            return tdocs;
        }
    };

    try {
        if (this.luceneSearchTimeout > 0) {
            TimeLimiter limiter = new SimpleTimeLimiter();
            docs = (TopDocs) limiter.callWithTimeout(search_call, this.luceneSearchTimeout, TimeUnit.SECONDS,
                    true);
        } else
            docs = (TopDocs) search_call.call();
    } catch (UncheckedTimeoutException e) {
        String msg = "Lucene search exceeded time limit ( " + this.luceneSearchTimeout + " seconds.)";
        if (sort != null)
            logger.warn(msg + "Query: {}, Sort: {}, Offset: {}, Limit: {}",
                    new Object[] { query, sort, offset, limit });
        else
            logger.warn(msg + "Query: {}, Offset: {}, Limit: {}", new Object[] { query, offset, limit });
        throw new ZepException(msg + e.getLocalizedMessage(), e);
    } catch (OutOfMemoryError oome) {
        throw oome;
    } catch (Exception e) {
        logger.error("Exception performing timed search: ", e);
        throw new ZepException(e.getLocalizedMessage(), e);
    }

    return docs;
}

From source file:com.facebook.presto.verifier.Validator.java

private QueryResult executeQuery(String url, String username, String password, Query query, String sql,
        Duration timeout, Map<String, String> sessionProperties) {
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        trySetConnectionProperties(query, connection);
        for (Map.Entry<String, String> entry : sessionProperties.entrySet()) {
            connection.unwrap(PrestoConnection.class).setSessionProperty(entry.getKey(), entry.getValue());
        }//from   www  .  ja v a  2s  .  c  om
        long start = System.nanoTime();

        try (Statement statement = connection.createStatement()) {
            TimeLimiter limiter = new SimpleTimeLimiter();
            Stopwatch stopwatch = Stopwatch.createStarted();
            Statement limitedStatement = limiter.newProxy(statement, Statement.class, timeout.toMillis(),
                    TimeUnit.MILLISECONDS);
            if (explainOnly) {
                sql = "EXPLAIN " + sql;
            }
            try (final ResultSet resultSet = limitedStatement.executeQuery(sql)) {
                List<List<Object>> results = limiter.callWithTimeout(getResultSetConverter(resultSet),
                        timeout.toMillis() - stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS,
                        true);
                return new QueryResult(State.SUCCESS, null, nanosSince(start), results);
            } catch (AssertionError e) {
                if (e.getMessage().startsWith("unimplemented type:")) {
                    return new QueryResult(State.INVALID, null, null, ImmutableList.<List<Object>>of());
                }
                throw e;
            } catch (SQLException | VerifierException e) {
                throw e;
            } catch (UncheckedTimeoutException e) {
                return new QueryResult(State.TIMEOUT, null, null, ImmutableList.<List<Object>>of());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw Throwables.propagate(e);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    } catch (SQLException e) {
        Exception exception = e;
        if (("Error executing query".equals(e.getMessage()) || "Error fetching results".equals(e.getMessage()))
                && (e.getCause() instanceof Exception)) {
            exception = (Exception) e.getCause();
        }
        State state = isPrestoQueryInvalid(e) ? State.INVALID : State.FAILED;
        return new QueryResult(state, exception, null, null);
    } catch (VerifierException e) {
        return new QueryResult(State.TOO_MANY_ROWS, e, null, null);
    }
}