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.netflix.curator.framework.recipes.atomic.TestDistributedAtomicLong.java

@Test
public void testSimulation() throws Exception {
    final int threadQty = 20;
    final int executionQty = 50;

    final AtomicInteger optimisticTries = new AtomicInteger();
    final AtomicInteger promotedLockTries = new AtomicInteger();
    final AtomicInteger failures = new AtomicInteger();
    final AtomicInteger errors = new AtomicInteger();

    final SummaryStatistics timingStats = new SynchronizedSummaryStatistics();
    List<Future<Void>> procs = Lists.newArrayList();
    ExecutorService executorService = Executors.newFixedThreadPool(threadQty);
    for (int i = 0; i < threadQty; ++i) {
        Callable<Void> proc = new Callable<Void>() {
            @Override/*from   ww  w .j ava  2s.c om*/
            public Void call() throws Exception {
                doSimulation(executionQty, timingStats, optimisticTries, promotedLockTries, failures, errors);
                return null;
            }
        };
        procs.add(executorService.submit(proc));
    }

    for (Future<Void> f : procs) {
        f.get();
    }

    System.out.println("OptimisticTries: " + optimisticTries.get());
    System.out.println("PromotedLockTries: " + promotedLockTries.get());
    System.out.println("Failures: " + failures.get());
    System.out.println("Errors: " + errors.get());
    System.out.println();

    System.out.println("Avg time: " + timingStats.getMean());
    System.out.println("Max time: " + timingStats.getMax());
    System.out.println("Min time: " + timingStats.getMin());
    System.out.println("Qty: " + timingStats.getN());

    Assert.assertEquals(errors.get(), 0);
    Assert.assertTrue(optimisticTries.get() > 0);
    Assert.assertTrue(promotedLockTries.get() > 0);
}

From source file:com.crossbusiness.resiliency.aspect.AnnotationAsyncAspectTest.java

@Test
public void method_returning_future_in_async_class_gets_routed_asynchronously_and_returns_a_future()
        throws InterruptedException, ExecutionException {
    ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation();
    Future<Integer> future = obj.incrementReturningAFuture();
    assertEquals(5, future.get().intValue());
    assertEquals(1, obj.counter);/*from  w ww.  j  a v a 2  s  .  c om*/
}

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

@Test
public void testRateLimitingHandlerQueueFull() throws ExecutionException, InterruptedException {
    latch.countDown();/*from w w w  .  j  av  a 2s  .  com*/
    latch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(N_THREADS * 2);
    try {
        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < N_THREADS * 2; ++i) {
            futures.add(executor.submit(new Callable<String>() {
                @Override
                public String call() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                        HttpResponse result = client.execute(get);
                        if (result.getStatusLine().getStatusCode() == 513) {
                            return "513";
                        }
                        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                        return HttpClientUtils.readResponse(result);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        Thread.sleep(300);
        latch.countDown();
        for (Future<?> future : futures) {
            String res = (String) future.get();
            Assert.assertTrue(res, res.equals("1") || res.equals("2") || res.equals("513"));
        }
        futures.clear();
        for (int i = 0; i < 2; ++i) {
            futures.add(executor.submit(new Callable<String>() {
                @Override
                public String call() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                        HttpResponse result = client.execute(get);
                        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                        return HttpClientUtils.readResponse(result);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }

        for (Future<?> future : futures) {
            String res = (String) future.get();
            Assert.assertTrue(res, res.equals("1") || res.equals("2"));
        }

    } finally {
        executor.shutdown();
    }

}

From source file:org.fast.maven.plugin.AssemblyMojo.java

/**
 * @throws MojoExecutionException//  w  w w  . j  a v a  2 s .c o  m
 *             thrown if modules are not found
 */
public void execute() throws MojoExecutionException {
    Properties prop = new Properties();
    prop.put("remoteUrlBase", outputDirectory.getAbsolutePath() + "/modules");
    prop.put("uriEncoding", charset);
    StaticDriver driver = new StaticDriver("modules", prop);
    try {
        checkStructure();
        init(driver);
        this.executor = Executors.newFixedThreadPool(this.threads);
        assemblePages(driver);
        copyStaticResources();

        this.executor.shutdown();
        this.executor.awaitTermination(10, TimeUnit.MINUTES);
        for (Future task : tasks) {
            task.get();
        }

    } catch (HttpErrorPage e) {
        throw new MojoExecutionException("Error", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error", e);
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Error", e);
    } catch (ExecutionException e) {
        throw new MojoExecutionException("Error", e);
    }
}

From source file:gov.ca.cwds.cals.service.ComplaintsService.java

@SuppressWarnings("squid:S2142") //Logging and informing client instead of shutdown
private List<ComplaintDto> aggregateComplaintsFromDifferentSources(String facilityNumber) {
    List<ComplaintDto> complaints = new ArrayList<>();

    ExecutorService executorService = Executors.newFixedThreadPool(3);
    try {/* w  w  w  . ja  v  a 2 s .  c o  m*/
        List<Future<List<ComplaintDto>>> futures = executorService.invokeAll(prepareListOfTasks(facilityNumber),
                1, TimeUnit.MINUTES);
        for (Future<List<ComplaintDto>> future : futures) {
            complaints.addAll(future.get());
        }
    } catch (InterruptedException e) {
        String message = "One of complaints execution threads has been interrupted";
        LOGGER.error(message, e);
        throw new ServiceException(message, e);
    } catch (ExecutionException e) {
        LOGGER.error(e.getMessage(), e);
        throw new ServiceException(e.getMessage(), e);
    }

    shutdownExecutionService(executorService);

    return complaints;
}

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

@Test
public void testConcurrentAccessSameKey() throws Exception {
    final KeyedBarrier<String, Object> barrier = new KeyedBarrier<String, Object>();

    final long waitTime = 1000;

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

    Future<?> future1 = execute(barrier, "key", callable1);

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

    future1.get();
    future2.get();/*from  w w w .j av  a2 s.  c o m*/

    /*
     * it can happen that runnable 2 has run before runnable 1 but the difference in time
     * should be more than waitTime
     */
    assertTrue(Math.abs(callable2.executionTime - callable1.executionTime) >= waitTime);
}

From source file:ok.MyService2.java

@Override
protected Task<BlockingQueue> createTask() {
    final Task<BlockingQueue> task;
    task = new Task<BlockingQueue>() {

        @Override/*ww  w  . ja  v  a2  s . com*/
        protected BlockingQueue call() throws Exception {
            BlockingQueue result = new LinkedBlockingQueue<String>();

            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(100);

            CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
            try {
                ExecutorService executor = Executors.newFixedThreadPool(sites.size());
                List<Future<String>> results = new ArrayList<Future<String>>();
                for (int i = 0; i < sites.size(); i++) {
                    HttpGet httpget = new HttpGet(sites.get(i));
                    Callable worker = new MyCallable(httpclient, httpget);
                    Future<String> res = executor.submit(worker);
                    results.add(res);
                    // String url = hostList[i];
                    //   Runnable worker = new MyRunnable(url);
                    //   executor.execute(worker);
                    //   executor.submit(null);

                }
                executor.shutdown();
                // Wait until all threads are finish
                //                   while (!executor.isTerminated()) {
                //
                //                   }
                for (Future<String> element : results) {
                    result.add(element.get());
                }
                System.out.println("\nFinished all threads");

            } finally {
                httpclient.close();
            }
            return result;
        }

    };
    return task;
}

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

@Test
public void doItNoFilters() throws ExecutionException, InterruptedException {

    byte[] data = new byte[2045];
    Random r = new Random();
    r.nextBytes(data);//from  w  ww.  ja va 2s.com
    ByteBuffer buffer = ByteBuffer.wrap(data);

    IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> {
        UUID startTime = UUIDs.timeBased();
        Future<UUID> id = queueClient.publish(new Item(startTime, buffer));
        try {
            id.get();
        } catch (Exception e) {
            fail(e.getMessage());
        }
    });

    IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> {
        Future<Optional<Item>> itemFuture = queueClient.consume();

        Optional<Item> item = null;
        try {
            item = itemFuture.get();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        assertTrue(item.isPresent());
    });

}

From source file:com.chingo247.structureapi.plan.schematic.SchematicManager.java

private void save(final List<File> schematics) {

    final List<SchematicData> data = new LinkedList<>();
    List<Future> tasks = new LinkedList<>();

    for (final File file : schematics) {
        tasks.add(executor.submit(new Runnable() {

            @Override/*ww w  .  j a  va2  s . co  m*/
            public void run() {
                try {
                    data.add(SchematicData.load(file));
                } catch (IOException | DataException ex) {
                    Logger.getLogger(SchematicManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }));
    }

    for (Future task : tasks) {
        try {
            task.get();
        } catch (InterruptedException | ExecutionException ex) {
            Logger.getLogger(SchematicManager.class.getName()).log(Level.SEVERE, null, ex);
            for (Future f : tasks) {
                f.cancel(true);
            }
        }
    }

    Session session = null;
    Transaction tx = null;
    try {
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
        for (SchematicData schematicData : data) {
            session.merge(schematicData);
        }
        tx.commit();
    } catch (HibernateException e) {
        try {
            tx.rollback();
        } catch (HibernateException rbe) {
            Logger.getLogger(AbstractService.class.getName()).log(Level.SEVERE,
                    "Couldnt roll back transaction", rbe);
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

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

@Test
public void testConcurrentAccessDifferentKey() throws Exception {
    final KeyedBarrier<String, Object> barrier = new KeyedBarrier<String, Object>();

    final long waitTime = 1000;

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

    Future<?> future1 = execute(barrier, "key", callable1);

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

    future1.get();
    future2.get();//  ww w .  java 2  s . c  o  m

    /*
     * it can happen that runnable 2 has run before runnable 1 but the difference in time
     * should not be more than 1 couple of milliseconds
     */
    assertTrue(Math.abs(callable2.executionTime - callable1.executionTime) < 100);
}