Skip to content

Instantly share code, notes, and snippets.

@mohanr
Created June 6, 2014 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohanr/43a6204640aaf86a1c0b to your computer and use it in GitHub Desktop.
Save mohanr/43a6204640aaf86a1c0b to your computer and use it in GitHub Desktop.
CompletableFuture example
import org.apache.http.HttpEntity;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment