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.github.lukaszbudnik.dqueue.QueueClientIntegrationTest.java

@Test
public void shouldPublishAndConsumeWithoutFilters() throws ExecutionException, InterruptedException {
    UUID startTime = UUIDs.timeBased();
    String name = "name 1";
    ByteBuffer contents = ByteBuffer.wrap(name.getBytes());

    Future<UUID> publishFuture = queueClient.publish(new Item(startTime, contents));
    publishFuture.get();

    Future<Optional<Item>> itemFuture = queueClient.consume();

    Optional<Item> item = itemFuture.get();

    UUID consumedStartTime = item.get().getStartTime();
    ByteBuffer consumedContents = item.get().getContents();

    assertEquals(startTime, consumedStartTime);
    assertEquals(contents, consumedContents);
}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java

@Test(expected = ExecutionException.class)
public void testRetryOnConflictExpectError() throws InterruptedException, ExecutionException {
    final String index = "JresUpdateDocumentTest.testRetryOnConflictExpectError".toLowerCase();
    final String type = "test";
    final String id = "warzone";

    final AtomicReference<String> error = new AtomicReference<String>();
    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    List<Future<?>> futures = new ArrayList<Future<?>>(numThreads);
    for (int i = 0; i < numThreads; i++) {
        futures.add(x.submit(new Callable<Void>() {
            @Override//from  w w  w .  ja  v a2  s . c  om
            public Void call() throws Exception {
                for (int j = 0; j < numIterations; j++) {
                    jres.quest(new JresUpdateDocument(index, type, id, ImmutableMap.of("value", 0)));
                }
                return null;
            }
        }));
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    for (Future<?> future : futures) {
        // expecting a conflict exception from ElasticSearch
        future.get();
    }
}

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

private Optional<Response> createConsumeResponse(Future<Optional<Item>> 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_FILTERS, Joiner.on(',').withKeyValueSeparator("=").join(i.getFilters()))
                .cacheControl(CacheControl.valueOf("no-cache")).build();
    });/*from   w  ww  .jav a  2 s.c om*/
}

From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java

@Override
public DomainObject get() throws PromiseBrokenException, InterruptedException {
    try {/*w ww  .java 2 s.  co m*/
        ServiceResponse<DomainObject> serviceResponse = new ServiceResponse<>();
        for (Future<TaskResult> futureResult : futureList) {
            TaskResult result = futureResult.get();
            if (result == null) {
                throw new PromiseBrokenException("Task result is null");
            }
            ServiceResponse<DomainObject> response = (ServiceResponse<DomainObject>) result.getData();
            if (!response.getIsSuccess())
                throw response.getException();
            serviceResponse.addData(response.getDataList());
        }
        if (responseMerger != null) {
            return responseMerger.mergeResponse(serviceResponse.getDataList());
        } else {
            return serviceResponse.getDataList().get(0);
        }
    } catch (ExecutionException exception) {
        checkAndThrowServiceClientException(exception);
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new InterruptedException(exception.getMessage());
    } catch (CancellationException exception) {
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new PromiseBrokenException(promiseBrokenException);
    }
}

From source file:io.undertow.server.handlers.JDBCLogDatabaseTestCase.java

@Test
public void testLogLotsOfThreadsToDatabase()
        throws IOException, InterruptedException, ExecutionException, SQLException {

    JDBCLogHandler logHandler = new JDBCLogHandler(HELLO_HANDLER, DefaultServer.getWorker(), "combined", ds);

    CompletionLatchHandler latchHandler;
    DefaultServer//from  w  ww .ja  va 2  s  .c  om
            .setRootHandler(latchHandler = new CompletionLatchHandler(NUM_REQUESTS * NUM_THREADS, logHandler));

    ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    try {
        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");
                            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();
    logHandler.awaitWrittenForTest();

    Connection conn = null;
    Statement statement = null;
    try {
        conn = ds.getConnection();
        statement = conn.createStatement();

        ResultSet resultDatabase = conn.createStatement().executeQuery("SELECT COUNT(*) FROM PUBLIC.ACCESS;");

        resultDatabase.next();
        Assert.assertEquals(resultDatabase.getInt(1), NUM_REQUESTS * NUM_THREADS);

    } finally {
        if (statement != null) {
            statement.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:com.graphhopper.jsprit.analysis.toolbox.ConcurrentBenchmarker.java

public void run() {
    System.out.println("start benchmarking [nuOfInstances=" + benchmarkInstances.size() + "][runsPerInstance="
            + runs + "]");
    double startTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
    List<Future<BenchmarkResult>> futures = new ArrayList<Future<BenchmarkResult>>();
    for (final BenchmarkInstance p : benchmarkInstances) {

        Future<BenchmarkResult> futureResult = executor.submit(new Callable<BenchmarkResult>() {

            @Override// ww  w  .j a  v  a  2s  .  co  m
            public BenchmarkResult call() throws Exception {
                return runAlgoAndGetResult(p);
            }

        });
        futures.add(futureResult);

    }
    try {
        int count = 1;
        for (Future<BenchmarkResult> f : futures) {
            BenchmarkResult r = f.get();
            print(r, count);
            results.add(f.get());
            count++;
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    executor.shutdown();
    print(results);
    System.out.println("done [time=" + (System.currentTimeMillis() - startTime) / 1000 + "sec]");
}

From source file:com.wst.cls.HttpAsyncClientDemo.java

private void sendPost() throws Exception {

    String url = "https://mestest.azurewebsites.net/EFFICIENCY_REPORT/Wip_Info_Active.aspx?PROVIDER_ID=1";
    try {//  w w  w. j  ava  2 s .  co m
        AsyncHttpClient ahc = new AsyncHttpClient();
        Future<Response> f = ahc.preparePost(url + "/offset").addParameter("cboWerks", "ATMU-System")
                .addParameter("cboUnit", "").addParameter("txtItemNo", "").addParameter("txtDeptday", "10")
                .execute();
        System.out.println("Response Code : " + f.get());
    } catch (IOException lException) {
        throw new RuntimeException(
                "IO Problems executing POST, underlying problem is " + lException.getMessage(), lException);
    }
}

From source file:com.easarrive.aws.plugins.common.service.impl.SQSNotificationService.java

/**
 * {@inheritDoc}//from ww w  . j  a  v  a  2s.  c o m
 */
@Override
public List<NotificationHandleResult<Message, Boolean>> handleNotification(Message message)
        throws AWSPluginException {
    try {
        if (message == null) {
            throw new AWSPluginException("The message is null");
        }
        if (notificationHandlerList == null) {
            throw new AWSPluginException("The notificationHandlerList is null for message (ID : %s)",
                    message.getMessageId());
        }
        if (notificationHandlerList.isEmpty()) {
            throw new AWSPluginException("The notificationHandlerList is empty for message (ID : %s)",
                    message.getMessageId());
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<List<NotificationHandleResult<Message, Boolean>>>> resultList = new ArrayList<Future<List<NotificationHandleResult<Message, Boolean>>>>();
        for (INotificationHandler<Message, Boolean> notificationHandler : notificationHandlerList) {
            Future<List<NotificationHandleResult<Message, Boolean>>> future = executorService
                    .submit(new NotificationHandlerCallable(notificationHandler, message));
            resultList.add(future);
        }

        List<NotificationHandleResult<Message, Boolean>> returnList = new ArrayList<NotificationHandleResult<Message, Boolean>>();
        //??
        for (Future<List<NotificationHandleResult<Message, Boolean>>> fs : resultList) {
            try {
                List<NotificationHandleResult<Message, Boolean>> result = fs.get();
                for (NotificationHandleResult<Message, Boolean> notificationHandleResult : result) {
                    returnList.add(notificationHandleResult);
                }
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error(e.getMessage(), e);
                }
                returnList.add(
                        new NotificationHandleResult<Message, Boolean>(message.getMessageId(), message, false));
            } finally {
                //????????
                executorService.shutdown();
            }
        }
        return returnList;
    } catch (Exception e) {
        throw new AWSPluginException(e.getMessage(), e);
    }
}

From source file:com.dell.doradus.db.s3.AmazonS3Service.java

private void wait(List<Future<?>> futures) {
    try {/*from w  ww.  j a  v  a2 s  . co m*/
        for (Future<?> future : futures) {
            future.get();
        }
    } catch (ExecutionException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}

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

@GET
@Path("/v1/logs/{key}")
@Produces(MediaType.TEXT_PLAIN)//from www. jav  a  2s  . com
public Response getLogs(final @PathParam("key") String key) {
    Stopwatch stopwatch = statsTimer.start();

    try {
        // increment request counter
        requestCounter.increment();

        // invoke service through Hystrix
        HystrixCommand<String> getCommand = new GetLogsCommand(key);
        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 get request.", ex);

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

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