Search code examples
guava

When to use Guava sameThreadExecutor


I just ran into a code like this:

ExecutorService executorService = MoreExecutors.sameThreadExecutor();

for (int i = 0; i < 10; i++) {
  executorService.submit(new Callable<Void>() {
    @Override
    public Void call() throws Exception {
      try {
        Do some work here...
        return null;
      } catch (final Exception e) {
        throw e;
      } finally {
        //
      }
    }
  });
}

Any difference between this and the code snippet below? If I understand it correctly, sameThreadExecutor uses the same thread that calls submit(), which means all these 10 "jobs" are run one by one on the main thread.

for (int i = 0; i < 10; i++) {
      try {
        Do some work here...
      } catch (final Exception e) {
        throw e;
      } finally {
        //
      }
}

Thanks!


Solution

  • First, MoreExecutors#sameThreadExecutor is deprecated:

    Deprecated. Use directExecutor() if you only require an Executor and newDirectExecutorService() if you need a ListeningExecutorService. This method will be removed in August 2016.

    So question is: when do you need MoreExecutors#directExecutor or MoreExecutors#newDirectExecutorService (difference between those two is mentioned above - ListeningExecutorService is Guava's extension for ListenableFutures). Answers are: