Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Guava sameThreadExecutor

Tags:

guava

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!

like image 959
gfytd Avatar asked Jul 13 '16 06:07

gfytd


1 Answers

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:

  • use it when you need Executor / ExecutorService (ex. your interface requires it) and don't want concurrency but rather run your multi-threaded code synchronously
  • (implied by above) use it in tests for predictable results
  • when you'd want to implement simple ExecutorService like newDirectExecutorService by yourself, but don't want to reinvent the wheel (see its source code)
  • if you're using ListenableFuture##addCallback(ListenableFuture, FutureCallback), newDirectExecutorService is used by default ("for use when the callback is fast and lightweight", also mentions it's "a dangerous choice in some cases" (see javadoc)).
like image 176
Xaerxess Avatar answered Sep 23 '22 02:09

Xaerxess