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 stubprivate static TextEditorServiceGrpc.TextEditorServiceBlockingStub stub =TextEditorServiceGrpc.newBlockingStub(channel);//call capitalize with blocking stubRequest request = Request.newBuilder().setText("hello world").build();Result response = stub.capitalize(request);System.out.println("Response received: "+ response.getText());
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 stubprivate static TextEditorServiceGrpc.TextEditorServiceStub asyncStub = TextEditorServiceGrpc.newStub(channel);//define responseObserver to handle asynchronous responseStreamObserver<Result> responseObserver = new StreamObserver<Result>() {@Overridepublic void onNext(Result value) {System.out.println("Response received: " + value.getText());}@Overridepublic void onError(Throwable t) {System.err.println("Error: " + t);}@Overridepublic void onCompleted() {System.out.println("Request completed");}};//call capitalize with asynchronous stubRequest request = Request.newBuilder().setText("hello world").build();asyncStub.capitalize(request, responseObserver);
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 ...