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.anrisoftware.globalpom.exec.core.DefaultProcessTask.java

private void waitForStreams(List<Future<?>> streamsTasks) throws InterruptedException, ExecutionException {
    for (Future<?> future : streamsTasks) {
        future.get();
    }/*from  w  w w .ja  v a2 s . c  o m*/
}

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

@RequestMapping(value = "/teller/withdraw", method = RequestMethod.POST)
@CountCalls/*from ww  w .  j  ava 2s  .c  om*/
public Callable<BalanceResponse> withdraw(@RequestBody final TellerRequest request) {
    return () -> {
        Future<Integer> future = tellerService.withdraw(request.getAccountId(), request.getCustomerId(),
                request.getAmount());
        return new BalanceResponse(request.getAccountId(), future.get());
    };
}

From source file:com.vmware.photon.controller.api.client.resource.TasksApi.java

/**
 * Get task details synchronously.//from  w  ww . j av a 2s.c  om
 *
 * @param taskId
 * @return
 * @throws IOException
 */
public Task getTask(final String taskId) throws IOException {
    String path = getBasePath() + "/" + taskId;

    Future<HttpResponse> response = this.restClient.performAsync(Method.GET, path, null /* payload */,
            null /* callback */);

    try {
        return parseGetTaskHttpResponse(response.get());
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.clustercontrol.monitor.util.StatusSearchRunUtil.java

@SuppressWarnings("unchecked")
public Map<String, ArrayList<ArrayList<Object>>> searchInfo(List<String> managerList, String facilityId,
        StatusFilterInfo filter) {/*from www .  j  a v  a  2s .c  om*/

    Map<String, ArrayList<ArrayList<Object>>> dispDataMap = new ConcurrentHashMap<>();
    Map<String, String> errMsgs = new ConcurrentHashMap<>();
    long start = System.currentTimeMillis();

    try {
        String threadName = Thread.currentThread().getName() + "-StatusSearch";
        List<StatusSearchTask> searchList = new ArrayList<StatusSearchTask>();
        for (String managerName : managerList) {
            StatusSearchTask task = null;
            task = new StatusSearchTask(threadName, managerName, facilityId, filter,
                    ContextProvider.getContext());
            searchList.add(task);
        }

        List<Future<Map<String, List<?>>>> list = getExecutorService().invokeAll(searchList);

        for (Future<Map<String, List<?>>> future : list) {
            if (future == null || future.get() == null) {
                continue;
            }
            Map<String, List<?>> map = future.get();
            for (Map.Entry<String, List<?>> entry : map.entrySet()) {
                //?1??
                String managerName = entry.getKey();
                List<?> ret = entry.getValue();

                if (ret.get(POS_INFO) != null && ret.get(POS_INFO) instanceof ArrayList) {
                    ArrayList<ArrayList<Object>> infoList = (ArrayList<ArrayList<Object>>) ret.get(POS_INFO);
                    dispDataMap.put(managerName, infoList);
                }
                if (ret.get(POS_ERROR) != null && ret.get(POS_ERROR) instanceof String) {
                    String errList = (String) ret.get(POS_ERROR);
                    errMsgs.put(managerName, errList);
                }
            }
        }
    } catch (InterruptedException e) {
        m_log.error(e.getMessage() + e.getClass().getName());
    } catch (ExecutionException e) {
        m_log.error(e.getMessage() + e.getClass().getName());
    }

    //
    if (0 < errMsgs.size()) {
        UIManager.showMessageBox(errMsgs, true);
    }

    long end = System.currentTimeMillis();
    m_log.debug("time=" + (end - start));
    return dispDataMap;
}

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

@Override
public void await() throws InterruptedException {
    try {/*from  w  w w  .  j  av a  2  s .  c o  m*/
        for (Future<TaskResult> future : futureList) {
            future.get();
        }
    } catch (ExecutionException exception) {
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new InterruptedException(exception.getMessage());
    } catch (CancellationException exception) {
        promiseBrokenException = new PromiseBrokenException(exception);
    }

}

From source file:com.aerofs.baseline.TestHttpIdInjection.java

@Test
public void shouldHaveChannelIdAndRequestIdInjectedIntoExceptionMapper() throws Exception {
    HttpGet get = new HttpGet(ServiceConfiguration.SERVICE_URL + "/exception");

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

    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_CONFLICT));

    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    ServiceError error = mapper.readValue(response.getEntity().getContent(), ServiceError.class);

    String tokens[] = error.getErrorText().split("-");
    assertThat(tokens.length, equalTo(2));
    assertThat(tokens[0].length(), greaterThan(0));
    assertThat(tokens[1].length(), greaterThan(0));

    // there's a channel id
    assertThat(tokens[0].length(), greaterThan(0));

    // the request id in the body matches the one that's added by the underlying pipeline
    String requestId = tokens[1];
    assertThat(requestId, equalTo(response.getFirstHeader(Headers.REQUEST_TRACING_HEADER).getValue()));
}

From source file:edumsg.netty.EduMsgNettyServerHandler.java

private synchronized void writeresponse(HttpObject currentObj, final ChannelHandlerContext ctx)
        throws JMSException, NumberFormatException, IOException, InterruptedException, JSONException,
        ExecutionException {//from  w  ww . j av  a2s . com

    JSONObject requestJson = new JSONObject(requestBody);
    NettyNotifier notifier = new NettyNotifier(this, requestJson.getString("queue"));
    //        notifier.start();
    sendMessageToActiveMQ(requestBody, requestJson.getString("queue"));

    System.out.println("waited");
    String oldResponseBody = responseBody;
    Future future = executorService.submit(notifier);
    this.responseBody = (String) future.get();
    //        System.out.println("handler: " + this.toString() + "\nnotifier: " + notifier.toString());
    //        synchronized (this) {
    //            wait();
    //        }
    //        notifier.join();
    //        if (responseBody == null)
    //            throw new JMSException("Error getting response body");
    System.out.println("notified");
    System.out.println("netty" + getResponseBody());
    System.out.println("-----------");
    JSONObject json = new JSONObject(getResponseBody());
    HttpResponseStatus status = null;
    if (!json.has("message"))
        status = new HttpResponseStatus(Integer.parseInt((String) json.get("code")),
                Integer.parseInt((String) json.get("code")) == 200 ? "Ok" : "Bad Request");
    else
        status = new HttpResponseStatus(Integer.parseInt((String) json.get("code")),
                (String) json.get("message"));

    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer(responseBody, CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
    if (keepAlive) {
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    ctx.writeAndFlush(response);
    //        channelReadComplete(ctx);
    //        notifyAll();
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testMultiClient() throws Exception {
    final Timing timing = new Timing();
    final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
    final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger max = new AtomicInteger(0);
    List<Future<Void>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < QTY; ++i) {
        Future<Void> future = service.submit(new Callable<Void>() {
            @Override//from   www .  j av a  2s  .co m
            public Void call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        timing.session(), timing.connection(), new RetryOneTime(1));
                try {
                    client.start();
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));
                } finally {
                    IOUtils.closeQuietly(client);
                }

                return null;
            }
        });
        futures.add(future);
    }

    for (Future<Void> f : futures) {
        f.get();
    }
    Assert.assertEquals(count.get(), 0);
    Assert.assertEquals(max.get(), QTY);
}

From source file:io.cloudslang.lang.cli.services.ConsolePrinterImplTest.java

@Test
public void testConsolePrint() throws Exception {
    final List<Runnable> runnableList = new ArrayList<>();
    final MutableInt mutableInt = new MutableInt(0);
    doAnswer(new Answer() {
        @Override//from  w w w  .  ja  v  a  2 s.c  o  m
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            mutableInt.increment();
            Object[] arguments = invocationOnMock.getArguments();
            runnableList.add((Runnable) arguments[0]);
            if (mutableInt.getValue() == 1) {
                return ConcurrentUtils.constantFuture("firstMessage");
            } else if (mutableInt.getValue() == 2) {
                return ConcurrentUtils.constantFuture("secondMessage");
            } else {
                return null;
            }
        }
    }).when(singleThreadExecutor).submit(Mockito.any(Runnable.class));

    consolePrinter.printWithColor(GREEN, "firstMessage");
    Future lastFuture = consolePrinter.printWithColor(GREEN, "secondMessage");

    assertEquals("secondMessage", lastFuture.get());

    assertEquals(2, runnableList.size());

    assertTrue(runnableList.get(0) instanceof ConsolePrinterImpl.ConsolePrinterRunnable);
    assertTrue(runnableList.get(1) instanceof ConsolePrinterImpl.ConsolePrinterRunnable);

    assertEquals(new ConsolePrinterImpl.ConsolePrinterRunnable(GREEN, "firstMessage"), runnableList.get(0));
    assertEquals(new ConsolePrinterImpl.ConsolePrinterRunnable(GREEN, "secondMessage"), runnableList.get(1));
}

From source file:com.github.lothar.security.acl.jpa.multithread.MultithreadCustomerRepositoryTest.java

private void waitForAssertions() throws InterruptedException {
    List<Future<String>> futures = executor.invokeAll(tasks);
    tasks.clear();/*from  w  w  w  .  j  av  a2  s .c o  m*/

    boolean fail = false;
    String message = "";
    for (Future<String> future : futures) {
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            message += e.getMessage() + "\n";
            fail = true;
        }
    }
    if (fail) {
        fail(message);
    }
}