本文整理汇总了Scala中java.util.concurrent.Executor类的典型用法代码示例。如果您正苦于以下问题:Scala Executor类的具体用法?Scala Executor怎么用?Scala Executor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Executor类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: FutureUtils
//设置package包名称以及导入依赖的类
package util
import java.util.concurrent.Executor
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Try
object FutureUtils {
import com.google.common.util.concurrent.{ListenableFuture => GuavaFuture}
def toFuture[T](f: GuavaFuture[T])(implicit executor: ExecutionContext): Future[T] = {
val pr = Promise[T]()
f.addListener(new Runnable {
def run() = pr.complete(Try(f.get()))
}, executor match {
case e: Executor => e
case _ => new ExecutionContextExecutor(executor)
})
pr.future
}
def toFutureUnit[T](f: GuavaFuture[T])(implicit executor: ExecutionContext): Future[Unit] = {
val pr = Promise[Unit]()
f.addListener(new Runnable {
def run() = pr.complete(Try(f.get()))
}, executor match {
case e: Executor => e
case _ => new ExecutionContextExecutor(executor)
})
pr.future
}
private class ExecutionContextExecutor(executonContext: ExecutionContext) extends java.util.concurrent.Executor {
def execute(command: Runnable): Unit = executonContext.execute(command)
}
}
示例2: ExecutionContextScheduler
//设置package包名称以及导入依赖的类
package reactor.core.scala.scheduler
import java.util.concurrent.Executor
import reactor.core.Disposable
import reactor.core.scheduler.Scheduler.Worker
import reactor.core.scheduler.{Scheduler, Schedulers}
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, ExecutionContextExecutorService}
class ExecutionContextScheduler private(val scheduler: Scheduler) extends Scheduler {
override def schedule(task: Runnable): Disposable = {
val cancellation = scheduler.schedule(task)
new Disposable {
override def dispose(): Unit = cancellation.dispose()
}
}
override def createWorker(): Worker = scheduler.createWorker()
}
object ExecutionContextScheduler {
def apply(executionContext: ExecutionContext): ExecutionContextScheduler = {
executionContext match {
case eces: ExecutionContextExecutorService => new ExecutionContextScheduler(Schedulers.fromExecutorService(eces))
case ece: ExecutionContextExecutor => new ExecutionContextScheduler(Schedulers.fromExecutor(ece))
case _ => new ExecutionContextScheduler(Schedulers.fromExecutor(new Executor {
override def execute(command: Runnable): Unit = executionContext.execute(command)
}))
}
}
}
示例3: BlockingExecutor
//设置package包名称以及导入依赖的类
package com.evaluni.txn_example.util
import java.util.concurrent.Executor
import scala.concurrent.ExecutionContext
class BlockingExecutor extends Executor {
def execute(command: Runnable): Unit = {
command.run()
}
}
trait MixInBlockingDatabaseExecutionContext {
val masterDatabaseExecutionContext: ExecutionContext = BlockingExecutionContext.global
val slaveDatabaseExecutionContext: ExecutionContext = BlockingExecutionContext.global
}
trait MixInBlockingExecutionContext {
implicit lazy val executionContext: ExecutionContext = BlockingExecutionContext.global
}
object BlockingExecutionContext {
val global: ExecutionContext = ExecutionContext.fromExecutor(new BlockingExecutor)
}
示例4: CacheOps
//设置package包名称以及导入依赖的类
package com.redbubble.util.cache
import java.util.concurrent.Executor
import com.github.benmanes.caffeine.cache.Caffeine
import com.redbubble.util.metrics.StatsReceiver
import scala.concurrent.duration.Duration
import scalacache.ScalaCache
import scalacache.serialization.InMemoryRepr
object CacheOps {
def newCache(name: String, maxSize: Long, ttl: Duration, executor: Executor)
(implicit statsReceiver: StatsReceiver): ScalaCache[InMemoryRepr] = {
val cache = Caffeine.newBuilder()
.maximumSize(maxSize)
.expireAfterWrite(ttl.length, ttl.unit)
.executor(executor)
.recordStats(() => new StatsCounter(sanitiseCacheName(name), statsReceiver))
.build[String, Object]
ScalaCache(new NonLoggingCaffeineCache(cache))
}
def sanitiseCacheName(n: String): String = n.replaceAll(" ", "_").toLowerCase
}
示例5: flush
//设置package包名称以及导入依赖的类
package com.redbubble.util.cache
import java.util.concurrent.{Executor, TimeUnit}
import com.redbubble.util.async.syntax._
import com.redbubble.util.cache.CacheOps.sanitiseCacheName
import com.redbubble.util.metrics.StatsReceiver
import com.twitter.util.Duration.fromSeconds
import com.twitter.util.{Duration, Future}
import scala.concurrent.ExecutionContext.fromExecutor
import scala.concurrent.duration.{Duration => ScalaDuration}
import scalacache.serialization.{Codec, InMemoryRepr}
import scalacache.{Flags, ScalaCache}
sealed trait MemoryCache {
def flush(): Future[Unit]
}
object MemoryCache {
final val DefaultWaitDuration: Duration = fromSeconds(5)
private val flags = Flags(readsEnabled = true, writesEnabled = true)
def newCache(name: String, maxSize: Long, ttl: Duration)(implicit ex: Executor, statsReceiver: StatsReceiver): MemoryCache =
new MemoryCache {
private val scalaTtl = ScalaDuration(ttl.inNanoseconds, TimeUnit.NANOSECONDS)
private val cache: ScalaCache[InMemoryRepr] = CacheOps.newCache(name, maxSize, scalaTtl, ex)(statsReceiver)
private val ec = fromExecutor(ex)
statsReceiver.scope(sanitiseCacheName(name)).addGauge("size")(estimatedSize.getOrElse(0L).toFloat)
sys.addShutdownHook(cache.cache.close())
override def caching[V](key: CacheKey)(f: => Future[V]) = {
val noOpCodec = Codec.anyToNoSerialization[V]
scalacache.cachingWithTTL[V, InMemoryRepr](key)(scalaTtl)(f.asScala)(cache, flags, ec, noOpCodec).asTwitter(ec)
}
override def put[V, Repr](key: CacheKey, value: V): Future[Unit] = {
val noOpCodec = Codec.anyToNoSerialization[V]
scalacache.put[V, InMemoryRepr](key)(value, Some(scalaTtl))(cache, flags, noOpCodec).asTwitter(ec)
}
override def get[V](key: CacheKey): Future[Option[V]] = {
val noOpCodec = Codec.anyToNoSerialization[V]
scalacache.get[V, InMemoryRepr](key)(cache, flags, noOpCodec).asTwitter(ec)
}
override def flush() = cache.cache.removeAll().asTwitter(ec)
private def estimatedSize = cache.cache match {
case NonLoggingCaffeineCache(underlying) => Some(underlying.estimatedSize())
case _ => None
}
}
}
示例6: AccessTokenCallCredentials
//设置package包名称以及导入依赖的类
package mu.node.echod.grpc
import java.util.concurrent.Executor
import io.grpc.{Attributes, CallCredentials, Metadata, MethodDescriptor}
class AccessTokenCallCredentials(accessToken: String) extends CallCredentials {
override def applyRequestMetadata(method: MethodDescriptor[_, _],
attributes: Attributes,
appExecutor: Executor,
applier: CallCredentials.MetadataApplier): Unit = {
appExecutor.execute(new Runnable {
override def run(): Unit = {
val headers = new Metadata()
val authorizationHeaderKey =
Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)
headers.put(authorizationHeaderKey, "Bearer " + accessToken)
applier.apply(headers)
}
})
}
}
示例7: ExecutorProxy
//设置package包名称以及导入依赖的类
package com.programmaticallyspeaking.ncd.infra
import java.lang.reflect.{InvocationHandler, InvocationTargetException, Method}
import java.util.concurrent.Executor
import org.slf4s.Logging
import scala.concurrent.{Await, Future, Promise}
import scala.reflect.ClassTag
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
class ExecutorProxy(executor: Executor) {
def createFor[A <: AnyRef : ClassTag](instance: A): A = {
val clazz = implicitly[ClassTag[A]].runtimeClass
java.lang.reflect.Proxy.newProxyInstance(clazz.getClassLoader, Array(clazz), new Handler(instance)).asInstanceOf[A]
}
class Handler(instance: AnyRef) extends InvocationHandler with Logging {
import scala.concurrent.ExecutionContext.Implicits._
private val className = instance.getClass.getName
override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]): AnyRef = {
val resultPromise = Promise[AnyRef]()
val before = System.nanoTime()
executor.execute(() => {
Try(method.invoke(instance, args: _*)) match {
case Success(f: Future[AnyRef]) => resultPromise.completeWith(f)
case Success(result) => resultPromise.success(result)
case Failure(t: InvocationTargetException) => resultPromise.failure(t.getCause)
case Failure(t) => resultPromise.failure(t)
}
})
resultPromise.future.onComplete { _ =>
val methodName = method.getName
val millis = (System.nanoTime() - before).nanos.toMillis
log.trace(s"Elapsed time for $className.$methodName = $millis ms")
}
if (classOf[Future[_]].isAssignableFrom(method.getReturnType)) resultPromise.future
else Await.result(resultPromise.future, 30.seconds) //TODO: Configurable
}
}
}
示例8: get
//设置package包名称以及导入依赖的类
package com.gdn.link.checker
import java.util.concurrent.Executor
import com.ning.http.client.AsyncHttpClient
import scala.concurrent.{Promise, Future}
trait WebClient {
def get(url: String)(implicit exec: Executor): Future[String]
}
case class BadStatus(code: Int) extends RuntimeException
object AsyncWebClient extends WebClient {
private val client = new AsyncHttpClient()
def get(url: String)(implicit exec: Executor): Future[String] = {
val f = client.prepareGet(url).execute()
val p = Promise[String]()
f.addListener(new Runnable {
def run() = {
val response = f.get
if (response.getStatusCode < 400)
p.success(response.getResponseBodyExcerpt(131072))
else p.failure(BadStatus(response.getStatusCode))
}
}, exec)
p.future
}
def shutdown(): Unit = {
client.closeAsynchronously()
}
}