StreamObservers in multi-thread Java application

42 views
Skip to first unread message

Quyen Pham Ngoc

unread,
Sep 7, 2023, 12:41:25 AM9/7/23
to grpc.io
I use grpc in Java multithread application. The documentation says: "Since individual StreamObservers are not thread-safe, if multiple threads will be writing to a StreamObserver concurrently, the application must synchronize calls." 

Is it true that with every onNext request of each StreamObservers I have to be thread-safe? What do I do when using StreamObserver in a multi-thread application environment? What happens if thread-safety is not guaranteed?

Sincerely thank you for your help

Terry Wilson

unread,
Sep 15, 2023, 3:55:09 PM9/15/23
to grpc.io
Yes, you should not have two threads calling onNext() on the same StreamObserver. If you do, you can get messages interleaved with each other and most likely just produce garbage. 

You need to make sure that your application acquires a lock before calling any of the methods on StreamObserver. Note that you CAN concurrently call the separate StreamObserver instances you have for incoming an outgoing messages. 

Quyen Pham Ngoc

unread,
Sep 18, 2023, 6:43:27 AM9/18/23
to grpc.io
Thanks for your help. 

I found a class that ensures synchronization of StreamObserver methods.
Link: https://github.com/stargate/stargate

public class SynchronizedStreamObserver<V> implements StreamObserver<V> {

  private final StreamObserver<V> streamObserver;

  public SynchronizedStreamObserver(StreamObserver<V> streamObserver) {
    this.streamObserver = streamObserver;
  }

  @Override
  public void onNext(V value) {
    synchronized (streamObserver) {
      streamObserver.onNext(value);
    }
  }

  @Override
  public void onError(Throwable t) {
    synchronized (streamObserver) {
      streamObserver.onError(t);
    }
  }

  @Override
  public void onCompleted() {
    synchronized (streamObserver) {
      streamObserver.onCompleted();
    }
  }
}
Reply all
Reply to author
Forward
0 new messages