Writing Async calls with Java 8
Say hello to Java 8 asynchronous library. This enables us to prepare calls that do not immediately return a response. CompletableFuture works like a promise, saying that this process will eventually end, but do not wait on it.
Let’s dive in to the details, below is the most basic example:
Notice we have a runnable function, that just prints out “DONE RUNNING” after iterating to 1000, we then have a CompletableFuture.runAsync accept that parameter, right below that asynchronous call is another print out.
Ideally: “Completely new thread” will run first before reaching “DONE RUNNING”:
runAsync specifies that we do not need to wait for the response to finish before continuing on. Some may argue that Runnable are running in a completely new thread either way hence the result, but runAsync can also used as below, which generally produces the same result:
The most powerful use of Completed Future is chaining asynchronous calls, for the example below, we have initialize, startDoingWork and shutdownMachine methods. in real world applications, this could mean, start the a third party service, or database connection, do the work, and then close the connection.
The tricky part here is knowing what chaining methods to use, if you notice on our previous examples we used runAsync method, now we are using supplyAsync, which accepts a Supplier, if you checked out the previous post on functions library, you’d know that Supplier returns an object. We then chain this return object using thenApply which takes in a Function (accepts and returns parameters), finally we use thenAccept that accepts a consumer (accepts parameter without any return).
See documentation: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html