CompletableFuture

The short definition of java.util.concurrent.CompletableFuture<T> is

A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

Code that conforms to the Reactive manifesto is all the rage now. The Play framework embodies it.

This example uses CompletableFuture and Apache HTTP Components to download data and react to its completion. I will update this as I learn more about the API and explain the asynchronous nature of this type of code.

public class ReactiveCompletion {

    ExecutorService executor = Executors.newFixedThreadPool(4);

    private void fetch() throws IOException{

        CountDownLatch latch = new CountDownLatch(1);
        CompletableFuture future =
        CompletableFuture.anyOf(CompletableFuture.supplyAsync(() -> streamData())
        .thenAccept(content -> {
            System.out.println("Completed");
            latch.countDown();
        })
        );
        try {
            latch.await();
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
    }

    private Content streamData(){
        Content content = null;
        try{
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet("http://data.gov.in/node/104089/datastore/export/json");
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Scanner in = new Scanner(new BufferedReader(new InputStreamReader(entity.getContent())));
                    while(in.hasNextLine() ){
                        System.out.println(in.nextLine());
                    }
                }
            } finally {
                response.close();
            }
        }catch (  IOException io){
            io.printStackTrace();
        }
        return content;
    }

    public static void main(String... argv) throws IOException {
        new ReactiveCompletion().fetch();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: