Executing listeners using MoreExecutors.directExecutor().

336 views
Skip to first unread message

testa...@gmail.com

unread,
Jun 14, 2016, 8:48:39 AM6/14/16
to grpc.io
Is it safe to execute a listener using MoreExecutors.directExecutor(), as in

ListenableFuture<MyResponse> res = myFutureStub.myMethod(myRequest);
res
.addListener(myCallback, MoreExecutors.directExecutor());

or may I run into problems using this pattern (as I'll be using gRPC's default executor's threads)? Most of the time myCallback only sets the value of a Spring's DeferredResult and returns, but in a few cases I can't address right now it will block the thread for a few milliseconds.

Eric Anderson

unread,
Jun 14, 2016, 12:40:35 PM6/14/16
to testa...@gmail.com, grpc.io
On Tue, Jun 14, 2016 at 5:48 AM, <testa...@gmail.com> wrote:
Is it safe to execute a listener using MoreExecutors.directExecutor(), as in

ListenableFuture<MyResponse> res = myFutureStub.myMethod(myRequest);
res
.addListener(myCallback, MoreExecutors.directExecutor());

We actually support it channel-wide with ManagedChannelBuilder.directExecutor(), but doing it per-call also works. It is safe as long as you don't block, which would be necessary for performance but is also important to avoid accidental deadlocks. 

When you are running with directExecutor, you are running on the network thread which may be shared with between multiple Channels and Servers.

or may I run into problems using this pattern (as I'll be using gRPC's default executor's threads)? Most of the time myCallback only sets the value of a Spring's DeferredResult and returns, but in a few cases I can't address right now it will block the thread for a few milliseconds.

If that blocking is a Thread.sleep() you should be fine (although you would want to reduce the blocking to improve performance/reduce latency). If you are blocking on other things, you need to make sure that you won't deadlock. If what you are blocking on is guaranteed to make progress, then it should be fine.
Reply all
Reply to author
Forward
0 new messages