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

Scala ExecutorService类代码示例

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

本文整理汇总了Scala中java.util.concurrent.ExecutorService的典型用法代码示例。如果您正苦于以下问题:Scala ExecutorService类的具体用法?Scala ExecutorService怎么用?Scala ExecutorService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ExecutorService类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
  }
} 
开发者ID:stefan-hering,项目名称:scalaserver,代码行数:24,代码来源:Server.scala


示例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) }
} 
开发者ID:F-kinungi,项目名称:Solutions,代码行数:53,代码来源:Task.scala


示例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();
  }
  
  
} 
开发者ID:walle-liao,项目名称:scala-examples,代码行数:51,代码来源:Server.scala


示例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[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:41,代码来源:ExecutorServiceBackboneCoordinator.scala


示例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)
  }
} 
开发者ID:sirthias,项目名称:swave,代码行数:40,代码来源:SwaveIdentityProcessorVerification.scala


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

} 
开发者ID:tockri,项目名称:hello-next,代码行数:32,代码来源:PooledContexts.scala


示例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())
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:29,代码来源:package.scala


示例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)
    }
  }
} 
开发者ID:peterjanovsky,项目名称:functional-examples,代码行数:55,代码来源:Executors.scala


示例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()
    }
  }
} 
开发者ID:rrramiro,项目名称:azure-sdk-for-scala,代码行数:52,代码来源:AzureTokenCredentials.scala


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


示例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)
  }
} 
开发者ID:bwsw,项目名称:sj-platform,代码行数:38,代码来源:TaskRunner.scala


示例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) 
开发者ID:timeoutdigital,项目名称:kamon-cloudwatch,代码行数:50,代码来源:MetricsShipper.scala


示例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
} 
开发者ID:hgiddens,项目名称:http4s-global-middleware,代码行数:34,代码来源:GlobalMiddleware.scala


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

} 
开发者ID:deenar,项目名称:fintest,代码行数:36,代码来源:RpcChannelImpl.scala


示例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) }
} 
开发者ID:deenar,项目名称:fintest,代码行数:58,代码来源:RpcServerImpl.scala


示例16: JamServer

//设置package包名称以及导入依赖的类
package ch.mirichan.jam.server

import java.util.concurrent.{ExecutorService, Executors}

import ch.mirichan.jam.server.storage.config.LocalFileConfigResource
import ch.mirichan.jam.server.storage.filesystem.LocalFilesystem

import scala.util.Properties.envOrNone
import scalaz.concurrent.Task
import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder


object JamServer extends ServerApp {

  val port : Int              = envOrNone("HTTP_PORT") map (_.toInt) getOrElse 8080
  val host : String           = "0.0.0.0"
  val pool : ExecutorService  = Executors.newCachedThreadPool()

  override def server(args: List[String]): Task[Server] = {
    val config = LocalFileConfigResource(LocalFilesystem).read
    BlazeBuilder
      .bindHttp(port, host)
      .mountService(RestApi.service)
      .withServiceExecutor(pool)
      .start
  }
} 
开发者ID:mirichan,项目名称:jam,代码行数:29,代码来源:JamServer.scala


示例17: util

//设置package包名称以及导入依赖的类
package ordinals

import java.util.Calendar
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.{ThreadFactory, Executors, TimeUnit, ExecutorService}

object util {
  final def addTimeStamp(str: String): String = Calendar.getInstance().getTime() + "  " + str

  def log(x: Any): Unit = println(addTimeStamp(x.toString))

  def logg(s: String)(x: Any): Unit = println(addTimeStamp(s + "\t= " + x.toString))

  final def logException(exce: Exception)(x: Any): Unit = System.err.println(addTimeStamp(x.toString + " = " + exce))

  // mod: positive remainder of division, i.e. mod(-3)(4) = 1 and mod(3)(4) = 3
  final def mod(n: Int)(m: Int): Int = ((n % m) + m) % m

  // some stuff for the executors
  final def esUnlimited: ExecutorService = Executors.newCachedThreadPool(new ThreadFactory {
    val counter = new AtomicInteger(0)

    def newThread(r: Runnable): Thread = {
      val t = new Thread(r, s"PAR-thread-${counter.getAndIncrement}")
      t.setDaemon(true)
      t
    }
  })


  final def shutExecService(debug: Boolean = false)(execService: ExecutorService): Unit = {
    if (debug) {
      logg("Shutting down now executor service")(execService.toString)
      logg(execService.toString + ".shutdown()")(execService.shutdown())
      logg(execService.toString + ".shutdownNow()")(execService.shutdownNow())
      if (!execService.awaitTermination(8, TimeUnit.SECONDS))
        logException(new Exception)("Executor Service did not terminate \n" + execService.toString)
      else logg("Executor terminated.")(execService.toString)
    }
    else {
      execService.shutdown()
      val x: java.util.List[Runnable] = execService.shutdownNow()
    }
  }
} 
开发者ID:kaelte,项目名称:playingWithScala,代码行数:46,代码来源:util.scala


示例18: attempt

//设置package包名称以及导入依赖的类
package todo.iomonad

import todo.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) }
} 
开发者ID:pchmiele,项目名称:fprogramming-in-scala,代码行数:53,代码来源:Task.scala


示例19: ClasspathExplorer

//设置package包名称以及导入依赖的类
package org.quicli.utils.reflect

import java.util.concurrent.{ExecutorService, Executors}

import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner
import io.github.lukehutch.fastclasspathscanner.matchprocessor.{ImplementingClassMatchProcessor, SubclassMatchProcessor}

import scala.reflect.ClassTag


object ClasspathExplorer {
  private val cpuCount: Int = Runtime.getRuntime.availableProcessors()
  private val scannerExecutor: ExecutorService = Executors.newFixedThreadPool(cpuCount * 2)
  private def cpScanner: FastClasspathScanner = new FastClasspathScanner("-jar:scala-*", "-jar:scalaz-*", "-jar:spec2-*")

  def findObjectsImplementing[I](implicit ct: ClassTag[I]): Set[I] = {
    val superType: Class[I] = ct.runtimeClass.asInstanceOf[Class[I]]

    val builder = Set.newBuilder[I]
    cpScanner.matchClassesImplementing(superType, new ImplementingClassMatchProcessor[I] {
      override def processMatch(subClass: Class[_ <: I]): Unit = {
        if (subClass.isObjectClass) {
          builder += subClass.getObject
        }
      }
    }).scan(scannerExecutor, cpuCount)

    builder.result()
  }

  def findConcreteClassesExtending[C](implicit ct: ClassTag[C]): Set[Class[_ <: C]] = {
    val superType: Class[C] = ct.runtimeClass.asInstanceOf[Class[C]]

    val builder = Set.newBuilder[Class[_ <: C]]
    cpScanner.matchSubclassesOf(superType, new SubclassMatchProcessor[C] {
      override def processMatch(subclass: Class[_ <: C]): Unit = {
        if(subclass.isConcrete) {
          builder += subclass
        }
      }
    }).scan(scannerExecutor, cpuCount)

    builder.result()
  }
} 
开发者ID:ovunccetin,项目名称:quicli,代码行数:46,代码来源:ClasspathExplorer.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala BeanProperty类代码示例发布时间:2022-05-23
下一篇:
Scala StringReader类代码示例发布时间: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