我正在使用Scala,它提供了自己的“执行上下文”抽象(与Java的Executor大致相同).我想与另一个需要ExecutorService的Java库进行交互.是否可以在Executor周围构造一个ExecutorService包装器?
我知道ExecutorService是Executor的子类.但在我的情况下,我只有后者,需要从中构建前者.
如果构造的ExecutorService不提供shutdown / await功能,那对我来说没问题.我真正关心的是在执行执行的情况下提交的合理实现.
解决方法:
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
原文地址:https://codeday.me/bug/20190628/1312043.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。