...

/

Exercise: Future Stub

Exercise: Future Stub

Implement the future stub for the unary RPC.

Understanding gRPC Stubs

gRPC provides three types of stubs to make remote procedure calls (RPCs) based on your application’s needs. These are blocking stubs, asynchronous stubs, and future stubs. Let’s delve into each of them to understand their purposes, differences, and use cases.

1. Blocking stubs

Blocking stubs, also known as synchronous stubs, make RPC calls in a blocking manner. This means the call will wait (or block) until a response is received from the server before proceeding to the next line of code.

Blocking stubs are typically used when the client needs to wait for a response before continuing with the next operation. This is straightforward to use and suitable for simple applications where the latency introduced by waiting is not a critical issue.

Blocking stubs do not support client-streaming or bidirectional-streaming RPCs.

We have used the blocking stub to call the capitalize unary RPC as follows:

//blocking stub
private static TextEditorServiceGrpc.TextEditorServiceBlockingStub stub =
TextEditorServiceGrpc.newBlockingStub(channel);
//call capitalize with blocking stub
Request request = Request.newBuilder().setText("hello world").build();
Result response = stub.capitalize(request);
System.out.println("Response received: "+ response.getText());
Using blocking stub to call unary RPC

2. Asynchronous stubs

Asynchronous stubs make non-blocking calls and immediately return. The response is handled via callbacks, allowing the client to continue processing other tasks while waiting for the server’s response.

Asynchronous stubs are used when the client needs to perform other tasks while waiting for the response or when the client needs to handle a high volume of requests without blocking each one.

The following code snippet shows a call to the capitalize unary RPC using the asynchronous stub:

//asynchronous stub
private static TextEditorServiceGrpc.TextEditorServiceStub asyncStub = TextEditorServiceGrpc.newStub(channel);
//define responseObserver to handle asynchronous response
StreamObserver<Result> responseObserver = new StreamObserver<Result>() {
@Override
public void onNext(Result value) {
System.out.println("Response received: " + value.getText());
}
@Override
public void onError(Throwable t) {
System.err.println("Error: " + t);
}
@Override
public void onCompleted() {
System.out.println("Request completed");
}
};
//call capitalize with asynchronous stub
Request request = Request.newBuilder().setText("hello world").build();
asyncStub.capitalize(request, responseObserver);
Using asynchronous stub to call unary RPC

3. Future stubs

Future stubs provide a way to make non-blocking calls that return a ListenableFuture. This allows the client to handle the response at a later time using the Future API. Future stubs combine some of the ...