java - 从 Executor 创建 ExecutorService

标签 java scala

我正在使用 Scala,它提供了自己的“执行上下文”抽象(与 Java 的 Executor 大致相同)。我想与另一个需要 ExecutorService 的 Java 库进行交互。是否可以围绕 Executor 构造一个 ExecutorService 包装器?

我知道 ExecutorServiceExecutor 的子类。但就我而言,我只有后者,需要从中构建前者。

如果构造的 ExecutorService 不提供关闭/等待功能,那对我来说没问题。我真正关心的是在给定 execute 实现的情况下合理地实现 submit

最佳答案

Turning an ExecutionContext to an ExecutorService (or rather and ExecutorService AND an ExecutionContext) using Scala 2.10+

import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService}
import java.util.concurrent.{ AbstractExecutorService, TimeUnit }
import java.util.Collections

object ExecutionContextExecutorServiceBridge {
  def apply(ec: ExecutionContext): ExecutionContextExecutorService = ec match {
    case null => throw null
    case eces: ExecutionContextExecutorService => eces
    case other => new AbstractExecutorService with ExecutionContextExecutorService {
      override def prepare(): ExecutionContext = other
      override def isShutdown = false
      override def isTerminated = false
      override def shutdown() = ()
      override def shutdownNow() = Collections.emptyList[Runnable]
      override def execute(runnable: Runnable): Unit = other execute runnable
      override def reportFailure(t: Throwable): Unit = other reportFailure t
      override def awaitTermination(length: Long,unit: TimeUnit): Boolean = false
    }
  }

或者尝试 Wrapping a scala.concurrent.ExecutionContext into java.concurrent.ExecutorService

关于java - 从 Executor 创建 ExecutorService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36358726/

相关文章:

java - 使用引用编译动态加载的类

java - 以下代码的 java 等效代码是什么?

java - 如何在测试期间不实例化假客户端?

java - 如何从我的代码中删除重复项

json - 如何设置内容类型?

scala - def 和 lambda 的 val 有什么区别?

scala - 通过交错值合并两个集合

java - Android - Google Analytics v4 命中生成但未发送

scala - 方法参数中具有抽象类型的特征

scala - 在scala中并行移动两条路径