本文整理汇总了Scala中java.util.concurrent.ExecutorService类的典型用法代码示例。如果您正苦于以下问题:Scala ExecutorService类的具体用法?Scala ExecutorService怎么用?Scala ExecutorService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ExecutorService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Server
//设置package包名称以及导入依赖的类
package sh.webserver
import java.net.ServerSocket
import java.util.concurrent.{ExecutorService, Executors}
import sh.webserver.request.Request
import scala.annotation.tailrec
class Server(port: Int) {
def start() {
val server = new ServerSocket(port)
val pool = Executors.newFixedThreadPool(8)
listen(server, pool)
}
@tailrec
private def listen(server : ServerSocket,pool : ExecutorService) {
val socket = server.accept()
pool.execute(new RequestHandler(socket))
listen(server, pool)
}
}
示例2: attempt
//设置package包名称以及导入依赖的类
package fpinscala.iomonad
import fpinscala.parallelism.Nonblocking._
import java.util.concurrent.ExecutorService
def attempt: Task[Either[Throwable,A]] =
Task(get map {
case Left(e) => Right(Left(e))
case Right(a) => Right(Right(a))
})
def handle[B>:A](f: PartialFunction[Throwable,B]): Task[B] =
attempt flatMap {
case Left(e) => f.lift(e) map (Task.now) getOrElse Task.fail(e)
case Right(a) => Task.now(a)
}
def or[B>:A](t2: Task[B]): Task[B] =
Task(this.get flatMap {
case Left(e) => t2.get
case a => IO(a)
})
def run(implicit E: ExecutorService): A = unsafePerformIO(get) match {
case Left(e) => throw e
case Right(a) => a
}
def attemptRun(implicit E: ExecutorService): Either[Throwable,A] =
try unsafePerformIO(get) catch { case t: Throwable => Left(t) }
}
object Task extends Monad[Task] {
def unit[A](a: => A) = Task(IO(Try(a)))
def flatMap[A,B](a: Task[A])(f: A => Task[B]): Task[B] =
a flatMap f
def fail[A](e: Throwable): Task[A] = Task(IO(Left(e)))
def now[A](a: A): Task[A] = Task(Return(Right(a)))
def more[A](a: => Task[A]): Task[A] = Task.now(()) flatMap (_ => a)
def delay[A](a: => A): Task[A] = more(now(a))
def fork[A](a: => Task[A]): Task[A] =
Task { par { Par.lazyUnit(()) } flatMap (_ => a.get) }
def forkUnit[A](a: => A): Task[A] = fork(now(a))
def Try[A](a: => A): Either[Throwable,A] =
try Right(a) catch { case e: Throwable => Left(e) }
}
示例3: Server
//设置package包名称以及导入依赖的类
package com.scala.examples.datagurn.lesson08
import com.scala.examples.datagurn.lesson07.Teacher
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import scala.concurrent.impl.Future
import java.util.concurrent.FutureTask
import scala.concurrent.impl.Future
import com.scala.examples.datagurn.lesson07.Teacher
object Server {
// ????????????
val executorService: ExecutorService = Executors.newFixedThreadPool(10);
val teachers: List[Teacher] = List(
new Teacher("t1", 20),
new Teacher("t2", 30),
new Teacher("t1", 25),
new Teacher("t1", 21)
);
def concurrentFilterByName(name: String): FutureTask[List[Teacher]] = {
val futures = new FutureTask[List[Teacher]](new Callable[List[Teacher]]() {
def call(): List[Teacher] = {
return filterByName(name);
}
})
executorService.execute(futures);
return futures; // ?? Future
}
def filterByName(name: String) : List[Teacher] = {
teachers.synchronized {
for {
item <- teachers
if item.name == name
} yield item
}
}
def main(args: Array[String]): Unit = {
val teachers : List[Teacher] = concurrentFilterByName("t1").get
println(teachers)
executorService.shutdown();
}
}
示例4: ExecutorServiceBackboneCoordinator
//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent
import java.util.concurrent.{ Callable, Future, ExecutorService }
import scala.util.Try
import scala.util.control.NonFatal
import org.slf4j.LoggerFactory
import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }
class ExecutorServiceBackboneCoordinator[DA](backbone: Backbone[DA], executor: ExecutorService) {
import ExecutorServiceBackboneCoordinator._
val localInitPhases = backbone.initializeTopLevelContexts
private class BackboneCallable(datum: DA) extends Callable[Xor[TransformationPipelineFailure, DA]] {
override def call(): Xor[TransformationPipelineFailure, DA] = {
val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
try {
backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
} finally {
releasePhases.foreach((phase: LocalReleasePhase) => {
Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
})
}
}
}
def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
executor.submit(new BackboneCallable(datum))
}
}
object ExecutorServiceBackboneCoordinator {
val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
}
示例5: SwaveIdentityProcessorVerification
//设置package包名称以及导入依赖的类
package swave.core.tck
import java.util.concurrent.{ExecutorService, Executors, TimeUnit}
import org.reactivestreams.Publisher
import org.reactivestreams.tck.{IdentityProcessorVerification, TestEnvironment}
import org.scalatest.testng.TestNGSuiteLike
import org.testng.SkipException
import org.testng.annotations.AfterClass
import swave.core._
abstract class SwaveIdentityProcessorVerification[T](val testEnv: TestEnvironment, publisherShutdownTimeout: Long)
extends IdentityProcessorVerification[T](testEnv, publisherShutdownTimeout) with TestNGSuiteLike
with StreamEnvShutdown {
def this(printlnDebug: Boolean) =
this(
new TestEnvironment(Timeouts.defaultTimeout.toMillis, printlnDebug),
Timeouts.publisherShutdownTimeout.toMillis)
def this() = this(false)
override def createFailedPublisher(): Publisher[T] =
Spout.failing[T](new Exception("Nope")).drainTo(Drain.toPublisher()).get
// Publishers created by swave don't support fanout by default
override def maxSupportedSubscribers: Long = 1L
override def required_spec313_cancelMustMakeThePublisherEventuallyDropAllReferencesToTheSubscriber(): Unit =
throw new SkipException("Not relevant for publisher w/o fanout support")
override lazy val publisherExecutorService: ExecutorService =
Executors.newFixedThreadPool(3)
@AfterClass
def shutdownPublisherExecutorService(): Unit = {
publisherExecutorService.shutdown()
publisherExecutorService.awaitTermination(3, TimeUnit.SECONDS)
}
}
示例6: PooledContexts
//设置package包名称以及导入依赖的类
package support
import java.util.concurrent.{ExecutorService, Executors, TimeUnit}
import scala.concurrent.ExecutionContext
object PooledContexts extends LoggerSupport {
private def newService(threadCount:Int):ExecutorService =
ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(threadCount))
private def ctx(service:ExecutorService) = ExecutionContext.fromExecutor(service)
private val db = newService(10)
implicit val dbContext:ExecutionContext = ctx(db)
private val app = newService(5)
implicit val appContext:ExecutionContext = ctx(app)
def shutdown(): Unit = {
Seq(db, app).foreach {svc =>
try {
svc.awaitTermination(Long.MaxValue, TimeUnit.NANOSECONDS)
} catch {
case ex:Exception => Logger.warn("termination failed", ex)
} finally {
svc.shutdownNow()
}
}
}
}
示例7:
//设置package包名称以及导入依赖的类
package com.twitter.finagle
import com.twitter.concurrent.NamedPoolThreadFactory
import com.twitter.finagle.util.ProxyThreadFactory
import com.twitter.util.Awaitable
import java.util.concurrent.{ExecutorService, Executors}
import org.jboss.netty.channel.socket.nio.NioWorkerPool
import org.jboss.netty.util.{ThreadNameDeterminer, ThreadRenamingRunnable}
package object netty3 {
// Disable Netty's thread name rewriting, to preserve the "finagle/netty3"
// suffix specified below.
ThreadRenamingRunnable.setThreadNameDeterminer(ThreadNameDeterminer.CURRENT)
val Executor: ExecutorService = {
val threadFactory = new ProxyThreadFactory(
new NamedPoolThreadFactory("finagle/netty3", makeDaemons = true),
ProxyThreadFactory.newProxiedRunnable(
() => Awaitable.enableBlockingTimeTracking(),
() => Awaitable.disableBlockingTimeTracking()
)
)
Executors.newCachedThreadPool(threadFactory)
}
private[netty3] val WorkerPool: NioWorkerPool = new NioWorkerPool(Executor, numWorkers())
}
示例8: ExecutorsForTesting
//设置package包名称以及导入依赖的类
import java.util.concurrent.{ExecutorService, Executors, TimeUnit}
import scala.concurrent.ExecutionContext
object ExecutorsForTesting {
class OurExecutorService(delegate: ExecutorService) extends java.util.concurrent.AbstractExecutorService {
override def shutdown: Unit = {
println("shutdown invoked")
delegate.shutdown()
}
override def execute(r: Runnable): Unit = {
println("--"*20 + "execute invoked")
delegate.execute(r)
}
override def awaitTermination(timeout: Long, timeUnit: TimeUnit): Boolean = {
println("await termination invoked")
delegate.awaitTermination(timeout, timeUnit)
}
override def isShutdown: Boolean = {
println("isShutdown invoked")
delegate.isShutdown
}
override def isTerminated: Boolean = {
println("isTerminated invoked")
delegate.isTerminated
}
override def shutdownNow: java.util.List[Runnable] = {
println("shutdownNow invoked")
delegate.shutdownNow()
}
}
val processors: Int = Runtime.getRuntime.availableProcessors
implicit val es = new OurExecutorService(Executors.newFixedThreadPool(processors))
implicit val ec = new ExecutionContext {
override def reportFailure(cause: Throwable): Unit = {
println(cause)
}
override def execute(runnable: Runnable): Unit = {
es.execute(runnable)
}
}
}
示例9: AzureTokenCredentials
//设置package包名称以及导入依赖的类
package fr.ramiro.azure
import java.util.concurrent.{ ExecutorService, Executors }
import com.microsoft.aad.adal4j.{ AuthenticationContext, AuthenticationResult, ClientCredential }
import com.microsoft.rest.credentials.TokenCredentials
import com.typesafe.config.{ Config, ConfigFactory }
object AzureTokenCredentials {
val AUTH_URL = "authURL"
def apply(config: Config = ConfigFactory.load()) = {
new AzureTokenCredentials(
config.getString(CLIENT_ID),
config.getString(TENANT_ID),
config.getString(CLIENT_KEY),
config.getString(AUTH_URL),
config.getString(MANAGEMENT_URI),
config.getString(BASE_URL)
)
}
}
class AzureTokenCredentials(
clientId: String,
domain: String,
secret: String,
authenticationEndpoint: String = "https://login.windows.net/",
tokenAudience: String = "https://management.core.windows.net/",
val baseUrl: String = "https://management.azure.com/"
) extends TokenCredentials(null, null) {
var authenticationResult: AuthenticationResult = null
override def getToken = {
if (authenticationResult == null || authenticationResult.getAccessToken == null) {
refreshToken()
}
authenticationResult.getAccessToken
}
override def refreshToken(): Unit = {
val executor: ExecutorService = Executors.newSingleThreadExecutor
try {
authenticationResult = new AuthenticationContext(authenticationEndpoint + domain, true, executor)
.acquireToken(tokenAudience, new ClientCredential(clientId, secret), null).get
} finally {
executor.shutdown()
}
}
}
示例10: runAsync
//设置package包名称以及导入依赖的类
package com.redbubble.util.async
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit._
import com.twitter.util._
trait AsyncOps {
final def runAsync[T](f: => T)(implicit fp: FuturePool): Future[T] = fp.apply(f)
final def runAsyncUnit[T](f: => T)(implicit futurePool: FuturePool): Unit = {
futurePool.apply(f)
()
}
final def block[T <: Awaitable[_]](awaitable: T): T = Await.ready(awaitable)
final def blockUnit[T <: Awaitable[_]](awaitable: T): Unit = {
block(awaitable)
()
}
final def shutdownExecutorService(executor: ExecutorService): Unit = {
executor.shutdown()
try {
executor.awaitTermination(10L, SECONDS)
} catch {
case _: InterruptedException => {
Console.err.println("Interrupted while waiting for graceful shutdown, forcibly shutting down...")
executor.shutdownNow()
}
}
()
}
}
object AsyncOps extends AsyncOps
示例11: createThreadPool
//设置package包名称以及导入依赖的类
package com.bwsw.sj.engine.core.engine
import java.util.concurrent.{ExecutorService, ExecutorCompletionService, Executors}
import com.bwsw.sj.common.utils.EngineLiterals
import com.google.common.util.concurrent.ThreadFactoryBuilder
import org.slf4j.LoggerFactory
trait TaskRunner {
private val logger = LoggerFactory.getLogger(this.getClass)
protected val threadName: String
private val threadPool: ExecutorService = createThreadPool(threadName)
protected val executorService = new ExecutorCompletionService[Unit](threadPool)
protected val blockingQueue: PersistentBlockingQueue = new PersistentBlockingQueue(EngineLiterals.persistentBlockingQueue)
private def createThreadPool(factoryName: String) = {
val countOfThreads = 3
val threadFactory = createThreadFactory(factoryName)
Executors.newFixedThreadPool(countOfThreads, threadFactory)
}
private def createThreadFactory(name: String) = {
new ThreadFactoryBuilder()
.setNameFormat(name)
.build()
}
def handleException(exception: Throwable) = {
logger.error("Runtime exception", exception)
exception.printStackTrace()
threadPool.shutdownNow()
System.exit(-1)
}
}
示例12: MetricsShipper
//设置package包名称以及导入依赖的类
package com.timeout.kamon.cloudwatch
import java.util.concurrent.{ExecutorService, Executors}
import akka.actor.Status.Failure
import akka.actor.{Actor, ActorLogging, Props}
import akka.event.LoggingReceive
import akka.pattern.pipe
import com.amazonaws.client.builder.ExecutorFactory
import com.amazonaws.regions.Regions
import com.amazonaws.services.cloudwatch.model.PutMetricDataResult
import com.amazonaws.services.cloudwatch.{AmazonCloudWatchAsync, AmazonCloudWatchAsyncClientBuilder}
import com.timeout.kamon.cloudwatch.KamonSettings.region
import com.timeout.kamon.cloudwatch.AmazonAsync.{MetricDatumBatch, MetricsAsyncOps}
import scala.concurrent.ExecutionContext
class MetricsShipper(implicit ec: ExecutionContext) extends Actor with ActorLogging {
// async aws client uses a thread pool that reuses a fixed number of threads
// operating off a shared unbounded queue.
implicit val client: AmazonCloudWatchAsync = AmazonCloudWatchAsyncClientBuilder
.standard()
.withRegion(
Option(Regions.getCurrentRegion).map(r => Regions.fromName(r.getName))
.getOrElse(Regions.fromName(region))
)
.withExecutorFactory(
new ExecutorFactory {
// don't use the default thread pool which configures 50 number of threads
override def newExecutor(): ExecutorService = Executors.newFixedThreadPool(KamonSettings.numThreads)
}
).build()
override def receive: Receive = LoggingReceive {
case ShipMetrics(metrics) => metrics.put.pipeTo(self)
case msg: PutMetricDataResult => log.debug(s"Succeeded to push metrics to Cloudwatch: $msg")
case Failure(t) => log.warning(s"Failed to send metrics to Cloudwatch ${t.getMessage}")
case msg => log.warning(s"Unsupported message $msg received in MetricsShipper")
}
}
object MetricsShipper {
def props(implicit ec: ExecutionContext): Props = Props(new MetricsShipper)
}
final case class ShipMetrics(datums: MetricDatumBatch)
示例13: Syntax
//设置package包名称以及导入依赖的类
package com.github.hgiddens.http4s.middleware.global
import java.net.InetSocketAddress
import java.util.concurrent.ExecutorService
import org.http4s.HttpService
import org.http4s.server.{HttpMiddleware, ServerBuilder}
object Syntax {
implicit class ServerBuilderExtensions(val builder: ServerBuilder) extends AnyVal {
def globalMiddleware(middleware: HttpMiddleware): ServerBuilder =
GlobalMiddlewareServerBuilder(builder, middleware)
}
}
private[global] case class GlobalMiddlewareServerBuilder(
underlying: ServerBuilder,
middleware: HttpMiddleware
) extends ServerBuilder {
type Self = GlobalMiddlewareServerBuilder
def bindSocketAddress(socketAddress: InetSocketAddress) =
copy(underlying = underlying.bindSocketAddress(socketAddress))
def withServiceExecutor(executor: ExecutorService) =
copy(underlying = underlying.withServiceExecutor(executor))
def mountService(service: HttpService, prefix: String = "") =
copy(underlying = underlying.mountService(middleware(service), prefix))
def start =
underlying.start
}
示例14: RpcChannelImpl
//设置package包名称以及导入依赖的类
package com.twitter.finagle.protobuf.rpc.impl
import java.util.concurrent.ExecutorService
import com.twitter.finagle.protobuf.rpc.RpcControllerWithOnFailureCallback
import com.twitter.finagle.protobuf.rpc.channel.ProtoBufCodec
class RpcChannelImpl(cb: ClientBuilder[(String, Message), (String, Message), Any, Any, Any], s: Service, executorService: ExecutorService) extends RpcChannel {
private val log = LoggerFactory.getLogger(getClass)
private val futurePool = FuturePool(executorService)
private val client: com.twitter.finagle.Service[(String, Message), (String, Message)] = cb
.codec(new ProtoBufCodec(s))
.unsafeBuild()
def callMethod(m: MethodDescriptor, controller: RpcController,
request: Message, responsePrototype: Message,
done: RpcCallback[Message]): Unit = {
val req = (m.getName(), request)
client(req) onSuccess { result =>
futurePool({done.run(result._2)})
} onFailure { e =>
log.warn("Failed. ", e)
controller.asInstanceOf[RpcControllerWithOnFailureCallback].setFailed(e)
}
}
def release() {
client.close()
}
}
示例15: RpcServerImpl
//设置package包名称以及导入依赖的类
package com.twitter.finagle.protobuf.rpc.impl
import com.twitter.finagle.protobuf.rpc.channel.ProtoBufCodec
import com.twitter.finagle.protobuf.rpc.RpcServer
import java.net.InetSocketAddress
import java.util.concurrent.ExecutorService
class RpcServerImpl(sb: ServerBuilder[(String, Message), (String, Message), Any, Any, Any], port: Int, service: Service, executorService: ExecutorService) extends RpcServer {
private val futurePool = FuturePool(executorService)
private val server: Server = ServerBuilder.safeBuild(ServiceDispatcher(service, futurePool),
sb
.codec(new ProtoBufCodec(service))
.name(getClass().getName())
.bindTo(new InetSocketAddress(port)))
def close(d: Duration) = {
server.close(d)
}
}
class ServiceDispatcher(service: com.google.protobuf.Service, futurePool: FuturePool) extends com.twitter.finagle.Service[(String, Message), (String, Message)] {
private val log = LoggerFactory.getLogger(getClass)
def apply(request: (String, Message)) = {
val methodName = request._1
val reqMessage = request._2
val m = service.getDescriptorForType().findMethodByName(methodName);
if (m == null) {
throw new java.lang.AssertionError("Should never happen, we already decoded " + methodName)
}
// dispatch to the service method
val task = {
var respMessage: Message = null
service.callMethod(m, null, reqMessage, new RpcCallback[Message]() {
def run(msg: Message) = {
respMessage = msg;
}
})
if (respMessage == null) throw new RuntimeException("Service Response message is required.")
(methodName, respMessage)
}
futurePool(task)
}
}
object ServiceDispatcher {
def apply(service: com.google.protobuf.Service, futurePool: FuturePool): ServiceDispatcher = { new ServiceDispatcher(service, futurePool) }
}