Convert blocking method to asynchronous

suggest change

The following method will take a second or two, depending on your connection, to retrieve a web page and count the text length. Whatever thread calls it blocks for that period. InputStreamReader uses the platform default charset, so the result is a character count, not a byte count. A checked IOException is wrapped in an unchecked RuntimeException, which is useful later.

public static long blockingGetWebPageLength(String urlString) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(urlString).openConnection().getInputStream()))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString().length();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

This converts it to a method that will return immediately by moving the blocking method call to another thread. By default the supplyAsync method will run the supplier on the common pool. For a blocking method this is probably not a good choice since one might exhaust the threads in that pool which is why I added the optional service parameter.

static private ExecutorService service = Executors.newCachedThreadPool();

static public CompletableFuture<Long> asyncGetWebPageLength(String url) {
    return CompletableFuture.supplyAsync(() -> blockingGetWebPageLength(url), service);
}

To use the method asynchronously, call one of the methods that accepts a lambda, such as thenAccept, and pass it the supplier's result when the future completes. Also use exceptionally or handle to log any exception.

public static void main(String[] args) {

    asyncGetWebPageLength("https://stackoverflow.com/")
            .thenAccept(l -> {
                System.out.println("Stack Overflow returned " + l);
            })
            .exceptionally((Throwable throwable) -> {
                Logger.getLogger("myclass").log(Level.SEVERE, "", throwable);
                return null;
            });

}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents