I'm using Scala, which provides its own "execution context" abstraction (roughly the same as Java's Executor
). I want to interact with another Java library which requires an ExecutorService
. Is it possible to construct an ExecutorService
wrapper around an Executor
?
I understand that ExecutorService
is a subclass of Executor
. But in my case I just have the latter and need to construct the former from it.
If the constructed ExecutorService
doesn't offer shutdown/await capabilities, that's fine with me. All I really care about is a sensible implementation of submit
given an implementation of execute
.
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
}
}
Or try Wrapping a scala.concurrent.ExecutionContext into java.concurrent.ExecutorService
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With