2016-04-01 20 views
4

Kendi "yürütme bağlamı" soyutlamasını (yaklaşık olarak Java'nın Executor ile aynı) sağlayan Scala kullanıyorum. ExecutorService gerektiren başka bir Java kütüphanesi ile etkileşim kurmak istiyorum. Executor etrafında bir ExecutorService sarıcı oluşturmak mümkün mü?Bir Yürütücüden bir ExecutorService oluşturun

ExecutorService'un Executor'un bir alt sınıfı olduğunu anlıyorum. Ama benim durumumda sadece ikincisine sahibim ve ondan eskiyi inşa etmem gerekiyor.

Oluşturulan ExecutorService, kapatma/bekletme özellikleri sunmuyorsa, bu benim için sorun değil. Gerçekten umurumda olan tek şey, execute'un uygulanmasıyla submit'un mantıklı bir uygulamasıdır.

cevap

2

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

Ya Wrapping a scala.concurrent.ExecutionContext into java.concurrent.ExecutorService mükemmel

+0

, teşekkürler deneyin! – larsrh