Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an ExecutorService from an Executor

Tags:

java

scala

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.

like image 972
larsrh Avatar asked Oct 19 '22 12:10

larsrh


1 Answers

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

like image 136
Andrzej Jozwik Avatar answered Oct 21 '22 06:10

Andrzej Jozwik