Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.