...

/

Using a Blocking Stub for Server Streaming RPC

Using a Blocking Stub for Server Streaming RPC

Learn how to switch from a nonblocking stub to a blocking stub for server streaming RPC.

Client stubs

Stubs are created by passing a Channelchannel_FTPServiceClient provided by the user. The stub uses this channel to send RPCs to the service. By now, we know that the asynchronous stub supports all four types of RPC API's. The blocking stub, on the other hand, supports only unary and server-streaming methods in the service definition. Blocking stubs do not support client-streaming or bidirectional-streaming RPCs.

Asynchronous stub

We have used an asynchronous stub in the FTPServiceClient class which is initialized using the newStub method in line 9 below.

public class FTPServiceClient implements AutoCloseable {
private FTPServiceGrpc.FTPServiceStub asyncStub;
private ManagedChannel channel;
private int chunkSizeInBytes;
private FTPServiceClient(FTPServiceClientBuilder builder) throws IOException {
//...
asyncStub = FTPServiceGrpc.newStub(channel);
}
//...
}
Initializing asyncStub in FTPServiceClient constructor

This asynchronous stub has been used to implement the unary deleteFile RPC (in the Client-side Implementation of Unary RPC lesson ) as well as the server streaming readFile RPC (in the Client-side Implementation of Server Streaming RPC lesson ). We can use a blocking stub instead for these RPCs. In that case, there are some differences in the manner in which the methods are called. Asynchronous method calls using an async stub, require a CountDownLatch for synchronization. There is no such requirement when using a blocking stub.

Blocking stub

Now, we will create a blocking stub. A blocking stub is instantiated via the newBlockingStub method by passing the channel in line 10 as follows:

public class FTPServiceClient implements AutoCloseable {
//...
private FTPServiceGrpc.FTPServiceStub stub;
private FTPServiceClient(FTPServiceClientBuilder builder) throws IOException {
//create channel
stub = FTPServiceGrpc.newBlockingStub(channel);
}
//...
}
Defining and initializing a blocking stub

The asynchronous stub signature for a server-streaming RPC method readFile is as follows:

public void readFile(MetaData request, StreamObserver<ReadFileResult> responseObserver)
readFile signature for asynchronous stub

The blocking stub signature for the readFile server-streaming RPC method does not contain a StreamObserver for the response. ...