14.3.2 Chaining Operation
The graph server (PGX) ships a version of Java 8's CompletableFuture
named
PgxFuture
, a monadic enhancement of the Future
interface.
The CompletableFuture
allows chaining of asynchronous computations without polling or the need of deeply nested callbacks (also known as callback hell). All PgxFuture
instances returned by PGX APIs are instances of CompletableFuture
and can be chained without the need of Java 8.
import java.util.concurrent.CompletableFuture
...
final GraphConfig graphConfig = ...
instance.createSessionAsync("my-session")
.thenCompose(new Fun<PgxSession, CompletableFuture<PgxGraph>>() {
@Override
public CompletableFuture<PgxGraph> apply(PgxSession session) {
return session.readGraphWithPropertiesAsync(graphConfig);
}
}).thenAccept(new Action<PgxGraph>() {
@Override
public void accept(PgxGraph graph) {
// do something with loaded graph
}
});
- The first line in the code makes an asynchronous call to
createSessionAsync()
to create a session.Once the promise is resolved, it returns a
PgxFuture
object, which is the newly createdPgxSession
. - The code then calls the
.thenCompose()
handler by passing a function which takes thePgxSession
object as an argument.Inside the function, there is another asynchronous
readGraphWithPropertiesAsync()
request which return anotherPgxFuture
object.The outer
PgxFuture
object returned by.thenCompose()
gets resolved when thereadGraphWithPropertiesAsync()
request completes. - This is followed by the
.thenAccept()
handler. The function that is passed to.thenAccept()
does not return anything. Therefore, thefuture
return type of.thenAccept()
isPgxFuture<Void>
.
Blocking Versus Chaining
For most use cases, you can block the caller thread. However, blocking can quickly lead to poor performance or deadlocks once things get more complex. As a rule, use blocking to quickly analyze selected graphs in a sequential manner, for example, in shell scripts or during interactive analysis using the interactive PGX shell.
Use chaining for applications built on top of PGX.
Parent topic: Handling Asynchronous Requests in Graph Server (PGX)