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!
First, MoreExecutors#sameThreadExecutor
is deprecated:
Deprecated. Use
directExecutor()
if you only require anExecutor
andnewDirectExecutorService()
if you need aListeningExecutorService
. 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 ListenableFuture
s). Answers are:
Executor
/ ExecutorService
(ex. your interface requires it) and don't want concurrency but rather run your multi-threaded code synchronouslyExecutorService
like newDirectExecutorService
by yourself, but don't want to reinvent the wheel (see its source code)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)).