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:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getArticlesAround(@RequestParam Double lat, @RequestParam Double lon)
        throws InterruptedException, ExecutionException, JsonProcessingException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(GEO_URL).queryParam("lat", lat.toString())
            .queryParam("lon", lon.toString());

    RestTemplate template = new RestTemplate();
    List<Map<String, Object>> geoResponse = template.getForObject(builder.build().encode().toUri(), List.class);

    Iterator<Map<String, Object>> it = geoResponse.iterator();
    List<Future<ResponseEntity<Map>>> jobs = new ArrayList<>();

    // to be able to merge answers from rating to geoitems there is a need 
    // to map the article to its articleID
    // (articleID) => (articleItem)
    Map<String, Map<String, Object>> mappedResponseObjects = new HashMap<>();
    while (it.hasNext()) {
        Map<String, Object> item = it.next();

        AsyncRestTemplate async = new AsyncRestTemplate();
        Future<ResponseEntity<Map>> futureResult = async.getForEntity((String) item.get("rating"), Map.class);
        jobs.add(futureResult);// w w  w. j  a  va  2  s  .com
        mappedResponseObjects.put((String) item.get("articleID"), item);
    }

    for (Future<ResponseEntity<Map>> job : jobs) {
        Map<String, Object> ratingMap = job.get().getBody();
        String articleID = (String) ratingMap.get("articleID");

        if ((Boolean) ratingMap.get("appropriate")) {
            mappedResponseObjects.get(articleID).putAll(ratingMap);
        } else {
            mappedResponseObjects.remove(articleID);
        }
    }

    WeightingPolicy policy = new WeightingPolicyImpl();
    List<Map<String, Object>> orderedResponse = policy.sortIncludingRating(mappedResponseObjects.values());
    List<Map<String, Object>> result = new ResponseMapFilterImpl().filter(orderedResponse);

    return new ResponseEntity<>(objectMapper.writeValueAsString(result), HttpStatus.OK);
}

From source file:org.piraso.server.spring.web.PirasoServletTest.java

@Test
public void testStartStopSuccess()
        throws IOException, ServletException, ExecutionException, InterruptedException {
    final AtomicBoolean fail = new AtomicBoolean(false);
    request.addParameter("service", "start");
    request.addParameter("preferences", mapper.writeValueAsString(new Preferences()));

    ExecutorService executor = Executors.newFixedThreadPool(2);

    Runnable startServiceRunnable = new Runnable() {
        public void run() {
            try {
                servlet.handleRequest(request, response);
            } catch (Exception e) {
                fail.set(true);/*w  w w .java  2s.  com*/
                e.printStackTrace();
            }
        }
    };

    Runnable logMessagesRunnable = new Runnable() {
        public void run() {
            try {
                MockHttpServletRequest request = CommonMockObjects.mockRequest(MONITORED_ADDR);
                request.addParameter("activity_uuid", "1");
                request.addParameter("service", "stop");

                // wait till service is available
                while (registry.getLogger(registry.createOrGetUser(pirasoRequest)) == null) {
                    Thread.sleep(100l);
                }

                servlet.handleRequest(request, new MockHttpServletResponse());
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

    Future future = executor.submit(startServiceRunnable);
    executor.submit(logMessagesRunnable);

    future.get();
    executor.shutdown();
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientIntegrationTest.java

@Test
public void shouldPublishAndConsumeWithManyFilter() throws ExecutionException, InterruptedException {
    // some filters
    Integer routingKey = 3;/* w w w  .j a va  2 s.  c om*/
    Integer version = 123;
    Integer type = 2;

    ImmutableMap.Builder<String, Object> filters = ImmutableMap.builder();
    filters.put("type", type).put("version", version).put("routing_key", routingKey);

    UUID startTime = UUIDs.timeBased();
    ByteBuffer contents = ByteBuffer.wrap("contents".getBytes());
    Future<UUID> publishFuture = queueClient.publish(new Item(startTime, contents, filters.build()));
    publishFuture.get();

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

    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.mycompany.crawlertest.GrabManager.java

private boolean checkPageGrabs() throws InterruptedException {
    Thread.sleep(PAUSE_TIME);//from w  w w  . ja v  a 2 s  . c om
    Set<GrabPage> pageSet = new HashSet<>();
    Iterator<Future<GrabPage>> iterator = futures.iterator();

    while (iterator.hasNext()) {
        Future<GrabPage> future = iterator.next();
        if (future.isDone()) {
            iterator.remove();
            try {
                pageSet.add(future.get());
            } catch (InterruptedException e) { // skip pages that load too slow
            } catch (ExecutionException e) {
            }
        }
    }
    for (GrabPage grabPage : pageSet) {
        addNewURLs(grabPage);
    }

    return (futures.size() > 0);
}

From source file:biz.fstechnology.micro.server.jms.AbstractJmsService.java

/**
 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
 *///from ww  w . ja va2 s.c o m
@Override
public void onMessage(Message message) {
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        if (((ObjectMessage) message).getObject() instanceof Result) {
            // no op
            return;
        }
        Request<?> request = (Request<?>) ((ObjectMessage) message).getObject(); // cast hell...
        Future<Request<?>> preProcessFuture = executor.submit(() -> onPreProcessRequest(request));

        Future<Result<?>> resultFuture = executor.submit(() -> processRequest(preProcessFuture.get()));

        Future<Result<?>> postProcessFuture = executor
                .submit(() -> onPostProcessRequest(request, resultFuture.get()));
        executor.shutdown();

        Result<?> result = postProcessFuture.get();

        ResponseMessageCreator messageCreator = new ResponseMessageCreator();
        messageCreator.setContents(result);
        messageCreator.setRequestId(message.getJMSCorrelationID());

        replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session));

    } catch (JMSException | InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Result<Object> result = new Result<>(e);
        try {
            ResponseMessageCreator messageCreator = new ResponseMessageCreator();
            messageCreator.setContents(result);
            messageCreator.setRequestId(message.getJMSCorrelationID());

            replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session));
        } catch (JmsException | JMSException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.kurento.kmf.test.base.GridBrowserMediaApiTest.java

public void runParallel(List<Node> nodeList, Runnable myFunc) throws InterruptedException, ExecutionException {
    ExecutorService exec = Executors.newFixedThreadPool(nodes.size());
    List<Future<?>> results = new ArrayList<>();
    for (int i = 0; i < nodes.size(); i++) {
        results.add(exec.submit(myFunc));
    }/* www .  j a  v a 2  s  .co  m*/
    for (Future<?> r : results) {
        r.get();
    }
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.GlobalMonitor.java

private void concurrentProcess(Map<Long, List<AlarmRule>> rules) {
    ExecutorCompletionService completionExecutor = new ExecutorCompletionService(executor);
    List<Future> futures = new ArrayList<Future>();
    for (Entry<Long, List<AlarmRule>> entry : rules.entrySet()) {
        final List<AlarmRule> alarmRules = entry.getValue();
        futures.add(completionExecutor.submit(new Callable<Object>() {

            @Override/* ww w  .  j av a2 s .c o m*/
            public Object call() throws Exception {
                pipelineMonitor.explore(alarmRules);
                return null;
            }
        }));
    }

    List<Throwable> exceptions = new ArrayList<Throwable>();
    int index = 0;
    int size = futures.size();
    while (index < size) {
        try {
            Future<?> future = completionExecutor.take();
            future.get();
        } catch (InterruptedException e) {
            exceptions.add(e);
        } catch (ExecutionException e) {
            exceptions.add(e);
        }
        index++;
    }

    if (!exceptions.isEmpty()) {
        StringBuilder sb = new StringBuilder(exceptions.size() + " exception happens in global monitor\n");
        sb.append("exception stack start :\n");
        for (Throwable t : exceptions) {
            sb.append(ExceptionUtils.getStackTrace(t));
        }
        sb.append("exception stack end \n");
        throw new IllegalStateException(sb.toString());
    }
}

From source file:com.reactive.hzdfs.TestRunner.java

@Test
public void testDistributedSimpleFileRecords() {
    try {/* w ww  . jav  a 2 s.c  o  m*/
        File f = ResourceLoaderHelper.loadFromFileOrClassPath("AirPassengers.csv");
        Future<DFSSResponse> fut = dfss.distribute(f, new DFSSTaskConfig());
        resp = fut.get();
        Assert.assertNotNull(resp);
        Assert.assertEquals("Records do not match", 145, resp.getNoOfRecords());
        Assert.assertTrue("error list not empty", resp.getErrorNodes().isEmpty());

    } catch (IOException e) {
        Assert.fail("Job did not start - " + e);
    } catch (InterruptedException e) {
        Assert.fail("InterruptedException - " + e);
    } catch (ExecutionException e) {
        Assert.fail("File distribution error - " + e.getCause());
    }

    Assert.assertNotNull(resp.getRecordMap());
    Object record = hzService.get(48, resp.getRecordMap());
    Assert.assertEquals("\"47\",1952.83333333333,172", record);
    record = hzService.get(1, resp.getRecordMap());
    Assert.assertEquals("\"\",\"time\",\"AirPassengers\"", record);
    record = hzService.get(145, resp.getRecordMap());
    Assert.assertEquals("\"144\",1960.91666666667,432", record);
}

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

@Test(expected = ExecutionException.class)
public void testRetryOnConflictExpectError() throws InterruptedException, ExecutionException {
    final String index = "JresUpdateDocumentScriptTest.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.  j  a  v a  2  s  .c  om
            public Void call() throws Exception {
                for (int j = 0; j < numIterations; j++) {
                    jres.quest(new JresUpdateDocumentScript(index, type, id, "ctx._source.value += 1", null,
                            ImmutableMap.of("value", 0), null));
                }
                return null;
            }
        }));
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

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

From source file:at.salzburgresearch.stanbol.enhancer.nlp.talismane.impl.TestTalismaneAnalyser.java

@Test
public void testConcurrentAnalyses() throws IOException, InterruptedException, ExecutionException {
    //warm up//w  w  w.  j  ava 2  s. c  o  m
    log.info("Start concurrent analyses test");
    log.info("  ... warm up");
    for (Entry<String, Blob> example : examples.entrySet()) {
        analyzer.analyse(example.getValue());
    }

    //performance test
    long start = System.currentTimeMillis();
    int concurrentRequests = 3;
    ExecutorService executor = Executors.newFixedThreadPool(concurrentRequests);
    int iterations = 100;
    log.info("  ... start test with {} iterations", iterations);
    List<Future<?>> tasks = new ArrayList<Future<?>>(iterations);
    long[] times = new long[iterations];
    Iterator<Blob> texts = examples.values().iterator();
    for (int i = 0; i < iterations; i++) {
        if (!texts.hasNext()) {
            texts = examples.values().iterator();
        }
        tasks.add(executor.submit(new AnalyzerRequest(i, times, analyzer, texts.next())));
    }
    for (Future<?> task : tasks) { //wait for completion of all tasks
        task.get();
    }
    long duration = System.currentTimeMillis() - start;
    log.info("Processed {} texts", iterations);
    log.info("  > time       : {}ms", duration);
    log.info("  > average    : {}ms", (duration) / (double) iterations);
    long sumTime = 0;
    for (int i = 0; i < times.length; i++) {
        sumTime = sumTime + times[i];
    }
    log.info("  > processing : {}ms", sumTime);
    float concurrency = sumTime / (float) duration;
    log.info("  > concurrency: {} / {}%", concurrency, concurrency * 100 / concurrentRequests);
}