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:CallableTask.java

public static void main(String[] args) throws Exception {
    // Get an executor with three threads in its thread pool
    ExecutorService exec = Executors.newFixedThreadPool(3);
    CallableTask task = new CallableTask(1);
    // Submit the callable task to executor
    Future<Integer> submittedTask = exec.submit(task);

    Integer result = submittedTask.get();
    System.out.println("Task's total  sleep time: " + result + "  seconds");
    exec.shutdown();//  ww w . j  av a  2 s .  c o  m
}

From source file:Main.java

public static void main(String[] args) {
    Callable<Object> badTask = () -> {
        throw new RuntimeException("Throwing exception from task execution...");
    };/*  w w  w.  j a va 2s.  c o m*/
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Future submittedTask = exec.submit(badTask);
    try {
        Object result = submittedTask.get();
    } catch (ExecutionException e) {
        System.out.println(e.getMessage());
        System.out.println(e.getCause().getMessage());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    exec.shutdown();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("test.txt");

    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
        int fileSize = (int) afc.size();
        ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);

        Future<Integer> result = afc.read(dataBuffer, 0);
        int readBytes = result.get();

        System.out.format("%s bytes read   from  %s%n", readBytes, path);
        System.out.format("Read data is:%n");

        byte[] byteData = dataBuffer.array();
        Charset cs = Charset.forName("UTF-8");
        String data = new String(byteData, cs);

        System.out.println(data);
    } catch (IOException ex) {
        ex.printStackTrace();//from  ww w .  j  av a2  s. c  o m
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(3);
    Future<Double> f = es.submit(new Task1());
    Future<Integer> f2 = es.submit(new Task2());

    System.out.println(f.get());
    System.out.println(f2.get());
    es.shutdown();/*from   w  w w  . java  2 s  .c o m*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
    SocketAddress serverAddr = new InetSocketAddress("localhost", 8989);
    Future<Void> result = channel.connect(serverAddr);
    result.get();
    System.out.println("Connected");
    Attachment attach = new Attachment();
    attach.channel = channel;/*from   w  w w .j a va 2 s . c o m*/
    attach.buffer = ByteBuffer.allocate(2048);
    attach.isRead = false;
    attach.mainThread = Thread.currentThread();

    Charset cs = Charset.forName("UTF-8");
    String msg = "Hello";
    byte[] data = msg.getBytes(cs);
    attach.buffer.put(data);
    attach.buffer.flip();

    ReadWriteHandler readWriteHandler = new ReadWriteHandler();
    channel.write(attach.buffer, attach, readWriteHandler);
    attach.mainThread.join();
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(3);
    Future<Double> f = es.submit(new Avg());
    Future<Integer> f2 = es.submit(new Factorial());

    System.out.println(f.get());
    System.out.println(f2.get());
    es.shutdown();//ww  w  . j  a va 2 s  . c  om
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientHttpExchange.java

public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//from w  w w. j  av a 2 s .  c  o m
        httpclient.start();
        HttpGet request = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }/*from   w w  w .j  a va  2  s.  com*/
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

From source file:httpasync.AsyncClientHttpExchange.java

public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//from ww w.  j  a  v  a2  s .co m
        httpclient.start();
        HttpGet request = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Response: " + response.getEntity().getContent());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:MyResult.java

public static void main(String[] args) throws Exception {
    // Get an executor with three threads in its thread pool
    ExecutorService exec = Executors.newFixedThreadPool(3);

    // Completed task returns an object of the TaskResult class
    ExecutorCompletionService<MyResult> completionService = new ExecutorCompletionService<>(exec);
    for (int i = 1; i <= 5; i++) {
        SleepingTask task = new SleepingTask(i, 3);
        completionService.submit(task);/*from w w  w. j a  v  a2  s . co m*/
    }
    for (int i = 1; i <= 5; i++) {
        Future<MyResult> completedTask = completionService.take();
        MyResult result = completedTask.get();
        System.out.println("Completed a  task - " + result);
    }
    exec.shutdown();
}