[concurrency-interest] CompletableFuture - cancel incomplete requests

Mohan Radhakrishnan radhakrishnan.mohan at gmail.com
Thu Jun 5 09:14:26 EDT 2014


Hi,
       I would like to wait for a HTTP response or content by connecting to
multiple sites. Can I use 'anyOf' to cancel all incomplete
requests(response is not received or not fully streamed) if any one
completes ? I will decide when something completes by returning from
streamData.

Do I need a latch here to make the VM wait ?
Does NIO.2's async. support use these types of futures ?



Thanks,
Mohan


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();
    }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140605/c45e0401/attachment.html>


More information about the Concurrency-interest mailing list