Example usage for java.util.concurrent Future get

List of usage examples for java.util.concurrent Future get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:com.fluxcapacitor.edge.jersey.resources.EdgeResource.java

private Response doAddLog(final String key, final String log) {
    Stopwatch stopwatch = statsTimer.start();

    try {// w  ww. j a v  a2 s  .  c o m
        // increment request counter
        requestCounter.increment();

        // invoke service through Hystrix
        HystrixCommand<String> getCommand = new AddLogCommand(key, log);

        Future<String> future = getCommand.queue();

        String responseString = future.get();

        // increment the fallback counter if the response came from a
        // fallback
        // TODO: this isn't needed as the hystrix framework exports its own
        // metrics on a per-command basis.
        // this is here for demo purposes.
        if (getCommand.isResponseFromFallback()) {
            fallbackCounter.increment();
        }

        // increment the timeout counter if the response timed out and
        // triggered fallback
        // TODO: this isn't needed as the hystrix framework exports its own
        // metrics on a per-command basis.
        // this is here for demo purposes.
        if (getCommand.isResponseTimedOut()) {
            timeoutCounter.increment();
        }

        // return response
        return Response.ok(responseString).build();
    } catch (Exception ex) {
        // add error counter
        errorCounter.increment();

        logger.error("Error processing the add request.", ex);

        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build();
    } finally {
        stopwatch.stop();

        statsTimer.record(stopwatch.getDuration(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
    }
}

From source file:com.github.lukaszbudnik.dqueue.jaxrs.service.QueueService.java

private Optional<Response> createConsumeOrderedResponse(Future<Optional<OrderedItem>> itemFuture)
        throws InterruptedException, java.util.concurrent.ExecutionException {
    return itemFuture.get().map(i -> {
        StreamingOutput streamingOutput = createStreamingOutput(i);
        return Response.ok(streamingOutput).header(X_DQUEUE_START_TIME_HEADER, i.getStartTime().toString())
                .header(X_DQUEUE_DEPENDENCY_HEADER, i.getDependency().toString())
                .header(X_DQUEUE_FILTERS, Joiner.on(',').withKeyValueSeparator("=").join(i.getFilters()))
                .cacheControl(CacheControl.valueOf("no-cache")).build();
    });//w  ww. ja v a2s  .  c  om
}

From source file:aos.camel.CamelFutureGetTest.java

@Test
public void testFutureGet() throws Exception {
    // now send the message to the endpoint in async manner
    // and get the Future handle back so we can later get the result
    LOG.info("Submitting task to Camel");
    Future<String> future = template.asyncRequestBody("seda:quote", "Hello Camel", String.class);
    LOG.info("Task submitted and we got a Future handle");

    // and get the answer (it will automatic wait for the task to be complete)
    String answer = future.get();
    LOG.info("The answer is: " + answer);
}

From source file:mitm.common.util.KeyedBarrierTest.java

@Test
public void testTimeout() throws Exception {
    final long timeout = 100;

    final KeyedBarrier<String, Object> barrier = new KeyedBarrier<String, Object>(10);

    final long waitTime = 1000;

    final SleepingCallable callable1 = new SleepingCallable(waitTime);
    final SleepingCallable callable2 = new SleepingCallable(waitTime);

    try {//from  www.j  ava2  s  .  com
        Future<?> future1 = execute(barrier, "key", callable1, timeout);

        Future<?> future2 = execute(barrier, "key", callable2, timeout);

        future1.get();
        future2.get();

        fail();
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof KeyedBarrierTimeoutException);
    }
}

From source file:io.undertow.server.handlers.accesslog.AccessLogFileTestCase.java

@Test
public void testLogLotsOfThreads() throws IOException, InterruptedException, ExecutionException {
    Path directory = logDirectory;
    Path logFileName = directory.resolve("server2.log");

    DefaultAccessLogReceiver logReceiver = new DefaultAccessLogReceiver(DefaultServer.getWorker(), directory,
            "server2.");
    CompletionLatchHandler latchHandler;
    DefaultServer.setRootHandler(latchHandler = new CompletionLatchHandler(NUM_REQUESTS * NUM_THREADS,
            new AccessLogHandler(HELLO_HANDLER, logReceiver, "REQ %{i,test-header}",
                    AccessLogFileTestCase.class.getClassLoader())));

    ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    try {/* ww  w  .j a  v  a2 s  .c o  m*/

        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < NUM_THREADS; ++i) {
            final int threadNo = i;
            futures.add(executor.submit(new Runnable() {
                @Override
                public void run() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        for (int i = 0; i < NUM_REQUESTS; ++i) {
                            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
                            get.addHeader("test-header", "thread-" + threadNo + "-request-" + i);
                            HttpResponse result = client.execute(get);
                            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                            final String response = HttpClientUtils.readResponse(result);
                            Assert.assertEquals("Hello", response);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        for (Future<?> future : futures) {
            future.get();
        }

    } finally {
        executor.shutdown();
    }
    latchHandler.await();
    logReceiver.awaitWrittenForTest();
    String completeLog = new String(Files.readAllBytes(logFileName));
    for (int i = 0; i < NUM_THREADS; ++i) {
        for (int j = 0; j < NUM_REQUESTS; ++j) {
            Assert.assertTrue(completeLog.contains("REQ thread-" + i + "-request-" + j));
        }
    }

}

From source file:com.mnxfst.testing.handler.exec.client.PTestPlanExecutorClient.java

/**
 * Executes the referenced test plan on all given hosts  
 * @param threads//from  w  w  w . j a va  2 s  .  c o m
 * @param recurrences
 * @param recurrenceType
 * @param testplan
 * @param hosts
 * @param port
 * @return
 */
protected Map<String, String> executeTestplan(int threads, int recurrences, String recurrenceType,
        byte[] testplan, String[] hosts, int port) {

    StringBuffer buf = new StringBuffer("/planexec?action=execute");
    buf.append("&threads=").append(threads);
    buf.append("&recurrences=").append(recurrences);
    buf.append("&recurrenceType=").append(recurrenceType);

    StringBuffer hn = new StringBuffer();
    for (int i = 0; i < hosts.length; i++) {
        hn.append(hosts[i]);
        if (i < hosts.length - 1)
            hn.append(", ");
    }

    System.out.println("Execute testplan:");
    System.out.println("\thostNames: " + hn.toString());
    System.out.println("\tport: " + port);
    System.out.println("\tthreads: " + threads);
    System.out.println("\trecurrences: " + recurrences);
    System.out.println("\trecurrenceType: " + recurrenceType);
    System.out.println("\n\turi: " + buf.toString());

    PTestPlanExecutorClientCallable callables[] = new PTestPlanExecutorClientCallable[hosts.length];
    for (int i = 0; i < hosts.length; i++) {
        callables[i] = new PTestPlanExecutorClientCallable(hosts[i], port, buf.toString(), testplan);
    }

    ExecutorService executorService = Executors.newFixedThreadPool(hosts.length);
    List<Future<NameValuePair>> executionResults = new ArrayList<Future<NameValuePair>>();
    try {
        executionResults = executorService.invokeAll(Arrays.asList(callables));
    } catch (InterruptedException e) {
        System.out.println("Test execution interrupted: " + e.getMessage());
    }

    // collect results from callables
    Map<String, String> result = new HashMap<String, String>();
    for (Future<NameValuePair> r : executionResults) {
        try {
            NameValuePair nvp = r.get();
            result.put(nvp.getName(), nvp.getValue());
        } catch (InterruptedException e) {
            System.out.println("Interrupted while waiting for results. Error: " + e.getMessage());
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println("Interrupted while waiting for results. Error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    return result;
}

From source file:benchmark.hbase.report.LoggingReport.java

@Override
public void aggregateAndPrintResults(BenchmarkType benchMarkType,
        CompletionService<Histogram> executorCompletionService, int numOfThreads, long numOfRecords,
        Stopwatch executorStartTime) {/*from  ww w .j a  va  2 s . c  om*/

    // Used to accumulate results from all histograms.
    final Histogram totalHistogram = Histograms.create();

    for (int i = 0; i < numOfThreads; i++) {
        try {
            final Future<Histogram> histogramFuture = executorCompletionService.take();
            Histogram histogram = histogramFuture.get();
            totalHistogram.add(histogram);
        } catch (final InterruptedException e) {
            log.error("Failed to retrieve data, got inturrupt signal", e);
            Thread.currentThread().interrupt();

            break;
        } catch (final ExecutionException e) {
            log.error("Failed to retrieve data", e);
        }
    }

    executorStartTime.stop();
    final long durationInSeconds = executorStartTime.elapsedTime(TimeUnit.SECONDS);
    final long durationInMs = executorStartTime.elapsedTime(TimeUnit.MILLISECONDS);
    // Using the durationInMs, since I would loose precision when using durationInSeconds.
    final long throughputPerSecond = 1000 * numOfRecords / durationInMs;

    final long min = totalHistogram.getMinValue();
    final double percentile25 = totalHistogram.getValueAtPercentile(25);
    final double percentile50 = totalHistogram.getValueAtPercentile(50);
    final double percentile75 = totalHistogram.getValueAtPercentile(75);
    final double percentile95 = totalHistogram.getValueAtPercentile(95);
    final double percentile99 = totalHistogram.getValueAtPercentile(99);
    final long max = totalHistogram.getMaxValue();
    final double mean = totalHistogram.getMean();
    final double stdDev = totalHistogram.getStdDeviation();
    final long totalMessagesCount = totalHistogram.getTotalCount();

    logInfo("=======================================");
    if (benchMarkType == BenchmarkType.READ_ONLY) {
        logInfo("READ ONLY BENCHMARK STATS");
    } else if (benchMarkType == BenchmarkType.WRITE_ONLY) {
        logInfo("WRITE ONLY BENCHMARK STATS");
    } else if (benchMarkType == BenchmarkType.READ_AND_WRITE) {
        logInfo("READ AND WRITE BENCHMARK STATS");
    } else {
        logInfo("UNKNOWN BENCHMARK STATS");
    }
    logInfo("=======================================");
    logInfo("DURATION (SECOND):      {}", durationInSeconds);
    logInfo("THROUGHPUT / SECOND:    {}", throughputPerSecond);
    logInfo("MIN:                    {}", min);
    logInfo("25th percentile:        {}", percentile25);
    logInfo("50th percentile:        {}", percentile50);
    logInfo("75th percentile:        {}", percentile75);
    logInfo("95th percentile:        {}", percentile95);
    logInfo("99th percentile:        {}", percentile99);
    logInfo("MAX:                    {}", max);
    logInfo("MEAN:                   {}", mean);
    logInfo("STD DEVIATION:          {}", stdDev);
    logInfo("CONCURRANCY:            {}", numOfThreads);
    logInfo("TotalRecords:           {}", totalMessagesCount);
    logInfo("\n\n\n");

}

From source file:cn.ctyun.amazonaws.services.s3.transfer.internal.UploadMonitor.java

private List<PartETag> collectPartETags() {
    final List<PartETag> partETags = new ArrayList<PartETag>(futures.size());
    for (Future<PartETag> future : futures) {
        try {//  w w w  . j  a v  a 2s  .  c o m
            partETags.add(future.get());
        } catch (Exception e) {
            throw new AmazonClientException("Unable to upload part: " + e.getCause().getMessage(),
                    e.getCause());
        }
    }
    return partETags;
}

From source file:dk.ange.octave.exec.OctaveExec.java

private RuntimeException getFromFuture(final Future<Void> future) {
    try {/*  w w  w. ja v  a  2 s.  c o m*/
        future.get();
    } catch (final InterruptedException e) {
        final String message = "InterruptedException should not happen";
        log.error(message, e);
        return new RuntimeException(message, e);
    } catch (final ExecutionException e) {
        if (e.getCause() instanceof OctaveException) {
            final OctaveException oe = (OctaveException) e.getCause();
            return reInstantiateException(oe);
        }
        // Can happen when there is an error in a OctaveWriter
        final String message = "ExecutionException should not happen";
        log.error(message, e);
        return new RuntimeException(message, e);
    } catch (final CancellationException e) {
        return e;
    } catch (final RuntimeException e) {
        final String message = "RuntimeException should not happen";
        log.error(message, e);
        return new RuntimeException(message, e);
    }
    return null;
}

From source file:org.sample.asyncclient.TestServlet.java

/**
 * Processes requests for both HTTP/*from  ww  w  .  j a v  a2  s .  c  o m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        final PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>JAX-RS 2 Async Client</h1>");
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://localhost:8080/filter/webresources/fruits");

        // Polling (Response)
        out.println("Invoking Future&lt;Response>...");
        Future<Response> r1 = target.request().async().get();
        out.println("<br>Received response (Future&lt;Response>): " + r1.get().readEntity(String.class));

        // Polling (String)
        out.println("<br>Invoking Future&lt;String>...");
        Future<String> r2 = target.request().async().get(String.class);
        out.println("<br>Received response (Future&lt;String>): " + r2.get());

        // Polling (String)
        out.println("<br>Invoking Future&lt;String>...");
        Future<String> r3 = target.request().async().get(String.class);
        out.println("<br>Received response (Future&lt;String>): " + r3.get());

        // Callback
        out.println("<br>Invoking InvocationCallback&lt;String>...");
        target.request().async().get(new InvocationCallback<String>() {

            @Override
            public void completed(String r) {
                System.out.println("Received response (InovcationCallback<String>): " + r);
            }

            @Override
            public void failed(Throwable t) {
                t.printStackTrace(out);
            }

        });
        out.print("<br>Check server.log for InvocationCallback&lt;String> results.");
        out.println("</body>");
        out.println("</html>");
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}