Bajji
Bajji

Reputation: 2383

Advantage of directExecutor

As far as I understand Guava's MoreExecutors.directExecutor() creates an Executor which will executes the runnable before the execute method call could return.

What are the usecases that need direct executor ? Can't the caller directly call runnable.run() directly instead of the extra level of indirection by creating an executor and submitting the runnable to this executor ? May be I am missing the real purpose of it's existence. I wanted to understand in what case is this useful.

Upvotes: 2

Views: 5974

Answers (3)

user1989849
user1989849

Reputation: 17

With Java 8+ we can pass Runnable::run in-place of MoreExecutors.directExecutor() to ListenableFuture.addListener or Futures.transform methods and the behavior will be identical.

Upvotes: 0

Max Poon
Max Poon

Reputation: 119

MoreExecutors.directExecutor() is useful when you call an API that requires you to specify an executor to execute the task (e.g. Futures.transform(), listenableFuture.addListener(), etc).

Note that when you use directExecutor() with these APIs, the runnable may be run on one of these two threads:

  • The thread that completes the previous future
  • The thread that calls transform()/addListener()

This uncertainty could cause unexpected issues. So be careful when you use directExecutor().

Upvotes: 3

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18825

There are few places which require both Runnable and Executor.

One of then is for example ListenableFuture and its addListener method. The only way how to execute listener immediately within the same thread is to provide direct executor.

Upvotes: 6

Related Questions