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:net.dryuf.concurrent.benchmark.SinglePostListenerAsyncBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)//  w w w  .java2  s .c  o m
@Measurement(iterations = 2, batchSize = 1)
@Fork(warmups = 1, value = 1)
public void benchmarkGuava() throws ExecutionException, InterruptedException {
    Executor directExecutor = MoreExecutors.directExecutor();
    com.google.common.util.concurrent.ListenableFutureTask<Integer>[] array = BenchmarkSupport
            .populateGuavaFutureArray(COUNT);
    BenchmarkSupport.threadedRunFutures(array);
    for (com.google.common.util.concurrent.ListenableFutureTask<Integer> f : array) {
        final Future<Integer> ff = f;
        f.addListener(() -> {
            try {
                ff.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
            }
        }, directExecutor);
    }
    // skip futures.get() as we already handled in listeners
}

From source file:net.dryuf.concurrent.benchmark.SinglePreListenerAsyncBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)/*ww  w .ja  v  a2 s . c  om*/
@Measurement(iterations = 2, batchSize = 1)
@Fork(warmups = 1, value = 1)
public void benchmarkGuava() throws ExecutionException, InterruptedException {
    Executor directExecutor = MoreExecutors.directExecutor();
    com.google.common.util.concurrent.ListenableFutureTask[] array = BenchmarkSupport
            .populateGuavaFutureArray(COUNT);
    for (com.google.common.util.concurrent.ListenableFutureTask f : array) {
        final Future<Integer> ff = f;
        f.addListener(() -> {
            try {
                ff.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
            }
        }, directExecutor);
    }
    BenchmarkSupport.threadedRunFutures(array);
    // skip futures.get() as we already handled in listeners
}

From source file:dk.clanie.actor.ActorAspectTest.java

/**
 * Tests retrieving the return value from an synchronously called method.
 * //from  w w w . j  a v a2s .c o m
 * @throws InterruptedException
 * @throws ExecutionException
 */
@Test
public void testGettingReturnValue() throws InterruptedException, ExecutionException {
    Future<Boolean> future = actor.methodReturningTrue();
    assertThat(future.get(), equalTo(Boolean.TRUE));
}

From source file:enmasse.broker.prestop.TopicMigrator.java

private void migrateMessages(String address, Map<String, Host> queueMap) throws Exception {
    List<Future<SubscriptionMigrator>> results = queueMap.entrySet().stream().map(
            e -> new SubscriptionMigrator(vertx, address, e.getKey(), localHost, e.getValue(), localBroker))
            .map(sub -> service.submit(sub)).collect(Collectors.toList());

    for (Future<SubscriptionMigrator> result : results) {
        try {//from  w  w w .  j  av  a  2 s  .co m
            result.get();
        } catch (Exception e) {
            System.out.println("Unable to migrate messages (ignoring): " + e.getMessage());
        }
    }
}

From source file:org.sakuli.services.receiver.gearman.GearmanResultServiceImpl.java

@Override
public void saveAllResults() {
    logger.info("======= SEND RESULTS TO GEARMAN SERVER ======");
    String hostname = properties.getServerHost();
    int port = properties.getServerPort();
    GearmanClient gearmanClient = getGearmanClient();
    GearmanJobServerConnection connection = getGearmanConnection(hostname, port);

    testSuite.refreshState();/*from   w w  w .  j  av a  2 s  . co  m*/
    NagiosCheckResult checkResult = nagiosCheckResultBuilder.build();

    String message = checkResult.getPayloadString();
    logger.info("MESSAGE for GEARMAN:\n{}", message);
    try {
        GearmanJob job = creatJob(checkResult);
        gearmanClient.addJobServer(connection);

        //send results to geraman
        Future<GearmanJobResult> future = gearmanClient.submit(job);
        GearmanJobResult result = future.get();
        if (result.jobSucceeded()) {
            gearmanClient.shutdown();
            logger.info("======= FINISHED: SEND RESULTS TO GEARMAN SERVER ======");
        } else {
            exceptionHandler
                    .handleException(NagiosExceptionBuilder.buildTransferException(hostname, port, result));
        }

    } catch (Throwable e) {
        logger.error(e.getMessage());
        exceptionHandler
                .handleException(NagiosExceptionBuilder.buildUnexpectedErrorException(e, hostname, port), true);
    }
}

From source file:com.aerofs.baseline.auth.TestAuthNoUserSpecifiedAuthenticators.java

@Test
public void shouldAllowAccessToUserResource() throws Exception {
    HttpUriRequest request = new HttpGet(ServiceConfiguration.SERVICE_URL + "/everyone");

    Future<HttpResponse> future = client.getClient().execute(request, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(Response.Status.OK.getStatusCode()));
    assertThat(HttpUtils.readResponseEntityToString(response), equalTo(UserResource.BORING));
}

From source file:cz.muni.fi.mir.services.TaskServiceImpl.java

@Override
public List<TaskStatus> getTasks() {
    List<TaskStatus> statuses = new ArrayList<>();
    for (Future<TaskStatus> future : entries.keySet()) {
        try {// ww w .  j av  a 2 s . c o m
            if (future.isDone()) {
                statuses.add(0, future.get());
            } else {
                statuses.add(0, entries.get(future).getStatus());
            }
        } catch (InterruptedException e) {
            logger.warn("Task was interrupted.", e);
        } catch (ExecutionException e) {
            logger.warn("Task threw exception.", e);
        }
    }
    return statuses;
}

From source file:com.amazonaws.services.kinesis.multilang.MessageWriterTest.java

@Test
public void writeInitializeMessageTest() throws IOException, InterruptedException, ExecutionException {
    Future<Boolean> future = this.messageWriter.writeInitializeMessage(shardId);
    future.get();
    Mockito.verify(this.stream, Mockito.atLeastOnce()).write(Mockito.any(byte[].class), Mockito.anyInt(),
            Mockito.anyInt());//from w ww . j  ava2s  . c o  m
    Mockito.verify(this.stream, Mockito.atLeastOnce()).flush();
}

From source file:co.paralleluniverse.fibers.httpasyncclient.FiberHttpAsyncClientTest.java

@Test
public void testAsync() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    final int concurrencyLevel = 20;
    // snippet client configuration
    final CloseableHttpAsyncClient client = FiberCloseableHttpAsyncClient.wrap(HttpAsyncClients.custom()
            .setMaxConnPerRoute(concurrencyLevel).setMaxConnTotal(concurrencyLevel).build());
    client.start();// w ww  .  ja v  a 2  s . c  o  m
    // end of snippet
    new Fiber<Void>(new SuspendableRunnable() {
        @Override
        public void run() throws SuspendExecution, InterruptedException {
            try {
                // snippet future calls
                ArrayList<Future<HttpResponse>> futures = new ArrayList<>();
                for (int i = 0; i < concurrencyLevel; i++)
                    futures.add(client.execute(new HttpGet("http://localhost:8080"), null));
                for (Future<HttpResponse> future : futures)
                    assertEquals("testGet", EntityUtils.toString(future.get().getEntity()));
                // end of snippet
            } catch (ExecutionException | IOException | ParseException ex) {
                fail(ex.getMessage());
            }
        }
    }).start().join(5000, TimeUnit.MILLISECONDS);
    client.close();
}

From source file:zarg.bank.rest.web.BankRestController.java

@RequestMapping(value = "/teller/deposit", method = RequestMethod.POST)
@CountCalls//from   ww w .j ava2 s.  co m
public Callable<BalanceResponse> deposit(@RequestBody final TellerRequest request) {
    return () -> {
        Future<Integer> future = tellerService.deposit(request.getAccountId(), request.getAmount());
        return new BalanceResponse(request.getAccountId(), future.get());
    };
}