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.DoublePreListenerAsyncBenchmark.java

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)/*  www . j av a 2 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[] 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);
        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:com.amazonaws.services.kinesis.multilang.MessageWriterTest.java

@Test
public void writeShutdownMessageTest() throws IOException, InterruptedException, ExecutionException {
    Future<Boolean> future = this.messageWriter.writeShutdownMessage(ShutdownReason.TERMINATE);
    future.get();

    Mockito.verify(this.stream, Mockito.atLeastOnce()).write(Mockito.any(byte[].class), Mockito.anyInt(),
            Mockito.anyInt());//from w  ww.  j  a  v  a 2 s.  com
    Mockito.verify(this.stream, Mockito.atLeastOnce()).flush();
}

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

@Test
public void writeProcessRecordsMessageTest() throws IOException, InterruptedException, ExecutionException {
    List<Record> records = new ArrayList<Record>() {
        {/*from   w w w . j  ava 2  s.  c  o m*/
            this.add(new Record() {
                {
                    this.setData(ByteBuffer.wrap("kitten".getBytes()));
                    this.setPartitionKey("some cats");
                    this.setSequenceNumber("357234807854789057805");
                }
            });
            this.add(new Record());
        }
    };
    Future<Boolean> future = this.messageWriter.writeProcessRecordsMessage(records);
    future.get();

    Mockito.verify(this.stream, Mockito.atLeastOnce()).write(Mockito.any(byte[].class), Mockito.anyInt(),
            Mockito.anyInt());
    Mockito.verify(this.stream, Mockito.atLeastOnce()).flush();
}

From source file:com.ironiacorp.http.impl.httpclient3.HttpJobRunnerHttpClient3.java

public void run() {
    ExecutorService executor = Executors.newFixedThreadPool(maxThreadsCount);
    ExecutorCompletionService<HttpJob> queue = new ExecutorCompletionService<HttpJob>(executor);
    List<Future<?>> workers = new ArrayList<Future<?>>();

    for (HttpJob job : jobs) {
        if (HttpMethod.GET == job.getMethod()) {
            GetRequest request = new GetRequest(httpClient, job);
            Future<HttpJob> jobStatus = queue.submit(request);
            workers.add(jobStatus);//from   w w w. j a v  a 2 s. co  m
            continue;
        }
        if (HttpMethod.POST == job.getMethod()) {
            PostRequest request = new PostRequest(httpClient, job);
            Future<HttpJob> jobStatus = queue.submit(request);
            workers.add(jobStatus);
            continue;
        }
        // TODO: job cannot be handled, what to do?
    }

    while (!workers.isEmpty()) {
        Iterator<Future<?>> i = workers.iterator();
        while (i.hasNext()) {
            try {
                Future<?> future = i.next();
                // future.get(timeout, TimeUnit.MILLISECONDS);
                future.get();
                i.remove();
                // } catch (TimeoutException e) {
            } catch (InterruptedException ie) {
                System.out.println(ie.getMessage());
            } catch (ExecutionException ee) {
                System.out.println(ee.getMessage());
                i.remove();
            }
        }
    }

    executor.shutdown();
}

From source file:cherry.chart.app.LineChartBatch.java

@Override
public ExitStatus execute(String... args) {

    int nThread = (args.length < 1 ? defaultNumThread : parseInt(args[0]));
    int count = (args.length < 2 ? defaultCount : parseInt(args[1]));

    ExecutorService executorService = Executors.newFixedThreadPool(nThread);
    List<Future<Boolean>> tasks = new LinkedList<>();

    for (int i = 0; i < count; i++) {

        final String numStr = String.valueOf(i);
        tasks.add(executorService.submit(new Callable<Boolean>() {
            @Override//from w  w w  . ja  v  a 2s .c o  m
            public Boolean call() {

                File f = new File(toDir, format(file, numStr));
                String t = format(title, numStr);

                CategoryDataset dataset = createDataset();
                JFreeChart chart = ChartFactory.createLineChart(t, xLabel, yLabel, dataset);

                try (OutputStream out = new FileOutputStream(f)) {
                    ChartUtilities.writeChartAsPNG(out, chart, width, height);
                    return true;
                } catch (IOException ex) {
                    log.error("failed to create file", ex);
                    return false;
                }
            }
        }));
    }

    boolean success = true;
    for (Future<Boolean> future : tasks) {
        try {
            success &= future.get();
        } catch (ExecutionException | InterruptedException ex) {
            log.error("failed to get result", ex);
            success = false;
        }
    }
    return (success ? ExitStatus.NORMAL : ExitStatus.ERROR);
}

From source file:com.uber.hoodie.common.util.queue.BoundedInMemoryExecutor.java

/**
 * Main API to run both production and consumption
 *///from ww  w. j  a va2 s .  c  om
public E execute() {
    try {
        ExecutorCompletionService<Boolean> producerService = startProducers();
        Future<E> future = startConsumer();
        // Wait for consumer to be done
        return future.get();
    } catch (Exception e) {
        throw new HoodieException(e);
    }
}

From source file:com.aerofs.baseline.json.TestJSONHandling.java

@Test
public void shouldReceiveErrorOnMakingPostWithEmptyBody() throws ExecutionException, InterruptedException {
    HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
    post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));

    Future<HttpResponse> future = client.getClient().execute(post, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_BAD_REQUEST));
}

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

@Test
public void writeCheckpointMessageWithErrorTest() throws IOException, InterruptedException, ExecutionException {
    Future<Boolean> future = this.messageWriter.writeCheckpointMessageWithError("1234", new Throwable());
    future.get();
    Mockito.verify(this.stream, Mockito.atLeastOnce()).write(Mockito.any(byte[].class), Mockito.anyInt(),
            Mockito.anyInt());/*from   www. ja  v a 2  s  . c om*/
    Mockito.verify(this.stream, Mockito.atLeastOnce()).flush();
}

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

@Test
public void streamIOExceptionTest() throws IOException, InterruptedException, ExecutionException {
    Mockito.doThrow(IOException.class).when(stream).flush();
    Future<Boolean> initializeTask = this.messageWriter.writeInitializeMessage(shardId);
    Boolean result = initializeTask.get();
    Assert.assertNotNull(result);// w  w  w  .  jav  a 2s  . c  o m
    Assert.assertFalse(result);
}

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

@Benchmark
@Warmup(iterations = WARMUP_ITERATIONS)/*ww  w  .  j a  v  a 2 s. com*/
@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);
    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);
    }
    // skip futures.get() as we already handled in listeners
}