Home > Software engineering >  gRPC streaming and thread safety
gRPC streaming and thread safety

Time:01-05

Say I'm using gRPC server-side streaming. If I send multiple client requests in a for loop, in this case on the server side, multiple threads will run the same service instance, and they will share the same StreamObserver object. If in one thread, the .onCompleted is called, will it prevent other threads from calling .onNext?

CodePudding user response:

StreamObserver is not thread-safe, so should never be called from multiple threads simultaneously. The service instance is called multiple times, one for each server-streaming RPC. (For server-streaming RPCs, that is the same as once per client request.) But each time it is called it receives a different StreamObserver instance. You can call the different instances on different threads.

Since each RPC has its own StreamObserver instance, calling onCompleted() on one RPC has no impact to being able to call onNext() for a different RPC. The important part is to not call onNext() after onCompleted() for a single RPC/StreamObserver instance.

  • Related