• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Executor类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了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)
  }

} 
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:42,代码来源:FutureUtils.scala


示例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)
      }))
    }
  }
} 
开发者ID:sinwe,项目名称:reactor-core-scala,代码行数:34,代码来源:ExecutionContextScheduler.scala


示例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)
} 
开发者ID:evaluni,项目名称:free-task,代码行数:24,代码来源:BlockingExecutionContext.scala


示例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
} 
开发者ID:redbubble,项目名称:finch-template,代码行数:27,代码来源:CacheOps.scala


示例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
      }
    }
} 
开发者ID:redbubble,项目名称:finch-template,代码行数:59,代码来源:MemoryCache.scala


示例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)
      }
    })
  }
} 
开发者ID:vyshane,项目名称:grpc-scala-microservice-kit,代码行数:24,代码来源:AccessTokenCallCredentials.scala


示例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
    }
  }
} 
开发者ID:provegard,项目名称:ncdbg,代码行数:48,代码来源:ExecutorProxy.scala


示例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()
  }

} 
开发者ID:situkangsayur,项目名称:link-checker,代码行数:37,代码来源:WebClient.scala



注:本文中的java.util.concurrent.Executor类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala StatusCode类代码示例发布时间:2022-05-23
下一篇:
Scala HttpService类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap