3
votes

Usually, the client can cancel the gRPC call with:

(requestObserver as ClientCallStreamObserver<Request>)
    .cancel("Cancelled", null)

However, it is shown in the Javadoc:

CancellableContext withCancellation = Context.current().withCancellation();
// do stuff
withCancellation.cancel(t);

Which one is the "correct" way of cancelling a client call, and letting the server know?

Edit:

To make matters more confusing, there's also ManagedChannel.shutdown*.

1

1 Answers

1
votes

Both are acceptable and appropriate.

clientCallStreamObserver.cancel() is generally easier as it has less boilerplate. It should generally be preferred. However, it is not thread-safe; it is like normal sending on the StreamObserver. It also requires direct awareness with the RPC; you can't have higher-level code orchestrate the cancellation as it may not even be aware of the RPC.

Use Context cancellation for thread-safe cancellation and less RPC-aware cancellation. Context cancellation could be used in circumstances similar to thread interruption or Future cancellation. Not that CancellableContexts should be treated as a resource and must be cancelled eventually to avoid leaking memory. (context.cancel(null) can be used when the context reaches its "normal" end of life.)