Search⌘ K
AI Features

Exercise: Future Stub

Explore how to implement gRPC future stubs to make non-blocking unary RPC calls using the ListenableFuture API. Learn to create future stubs, make RPC calls, attach listeners, and handle asynchronous responses effectively in Java. This lesson helps you understand the differences between blocking, asynchronous, and future stubs and guides you to test your future stub implementation in a text editor service example.

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 ...