从 Executor 创建 ExecutorService

5
我正在使用Scala,它提供了自己的“执行上下文”抽象(大致等同于Java的Executor)。我想与另一个需要ExecutorService的Java库进行交互。是否可以在Executor周围构建一个ExecutorService包装器呢?
我知道ExecutorServiceExecutor的子类。但在我的情况下,我只有后者,需要从中构建前者。
如果构造的ExecutorService没有提供shutdown/await能力,对我来说没问题。我真正关心的是,在给定execute的实现的情况下,submit的合理实现。
1个回答

3

使用Scala 2.10+将ExecutionContext转换为ExecutorService(或者更确切地说是ExecutorService和ExecutionContext)

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
    }
  }

或者尝试将scala.concurrent.ExecutionContext封装成java.concurrent.ExecutorService


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接