Chapter 7. Asynchronous Programming, Promises, and Executions
Asynchronous frameworks for the JVM are plagued by the fact that Java has no language-level support for continuations. This means that when asynchronous APIs are employed, a callback handler (or “completion handler”) must be provided to the receiver in order to return the data to the caller. This invoke-and-callback process introduces a nondeterministic data flow, where concurrency must be carefully considered when building and returning data. It also introduces nondeterminism to the processing control flow, where it can be difficult, if not impossible, for the framework to know whether an asynchronous operation is still processing.
Consider the code in Example 7-1, which outlines the contract for an asynchronous service, and shows the associated user code.
Example 7-1. An asynchronous demonstration using a callback
publicinterfaceAsyncDatabaseService{voidfindByUsername(Stringusername,Consumer<User>callback);}RatpackServer.start(spec->spec.registry(...).handlers(chain->chain.get(":username",ctx->{AsyncDatabaseServicedb=ctx.get(AsyncDatabaseService.class);Stringusername=ctx.getPathTokens().get("username");db.findByUsername(username,user->{ctx.render(user);});})));
Let’s ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access