When to use Guava sameThreadExecutor

I just came across this code:

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 { // } } }); } 

The difference between this and the code snippet below? If I understand it correctly, the sameThreadExecutor uses the same thread that calls submit (), which means that all these 10 "jobs" are started one after another in the main thread.

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

Thanks!

+5
source share
1 answer

First, MoreExecutors#sameThreadExecutor deprecated:

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

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

+5
source

All Articles