guava - 何时使用 Guava SameThreadExecutor

标签 guava

我刚刚遇到这样的代码:

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

这和下面的代码片段有什么区别吗?如果我理解正确的话,sameThreadExecutor使用调用submit()的同一个线程,这意味着所有这10个“作业”都在主线程上一一运行。

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

谢谢!

最佳答案

首先,MoreExecutors#sameThreadExecutor已弃用:

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

所以问题是:你什么时候需要 MoreExecutors#directExecutorMoreExecutors#newDirectExecutorService (上面提到了两者之间的区别 - ListeningExecutorService 是 Guava 对 ListenableFuture 的扩展)。答案是:

关于guava - 何时使用 Guava SameThreadExecutor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38344157/

相关文章:

java - Java如何保证ListenableFuture中future.isDone()时回调被调用

java - 是否可以将 Guava 的 ForwardingListIterator 与 PeekingIterator 结合使用?

java - 创建一个映射/缓存,它将使用默认构造函数生成的对象作为新键

java - Guava:如何结合过滤和变换?

java - Guava RateLimiter 预热说明

java - 使用 Java Guava 库,如何使用 Builder 创建 ImmutableSortedSet?

java - 为什么这个文件无法删除?

java - 编程 - Java - 将合并算法与操作分离

java - 从一个 POJO 列表转换为另一个 POJO

maven - 在 guava-libraries 项目上运行 "mvn compile"后如何解决错误?