本文整理汇总了Scala中java.util.concurrent.CountDownLatch类的典型用法代码示例。如果您正苦于以下问题:Scala CountDownLatch类的具体用法?Scala CountDownLatch怎么用?Scala CountDownLatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CountDownLatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: PinnedActorSpec
//设置package包名称以及导入依赖的类
package akka.actor.dispatch
import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.testkit._
import akka.actor.{ Props, Actor }
import akka.testkit.AkkaSpec
import org.scalatest.BeforeAndAfterEach
import akka.dispatch.{ PinnedDispatcher, Dispatchers }
import scala.concurrent.Await
import akka.pattern.ask
object PinnedActorSpec {
val config = """
pinned-dispatcher {
executor = thread-pool-executor
type = PinnedDispatcher
}
"""
class TestActor extends Actor {
def receive = {
case "Hello" ? sender() ! "World"
case "Failure" ? throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
}
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class PinnedActorSpec extends AkkaSpec(PinnedActorSpec.config) with BeforeAndAfterEach with DefaultTimeout {
import PinnedActorSpec._
private val unit = TimeUnit.MILLISECONDS
"A PinnedActor" must {
"support tell" in {
var oneWay = new CountDownLatch(1)
val actor = system.actorOf(Props(new Actor { def receive = { case "OneWay" ? oneWay.countDown() } }).withDispatcher("pinned-dispatcher"))
val result = actor ! "OneWay"
assert(oneWay.await(1, TimeUnit.SECONDS))
system.stop(actor)
}
"support ask/reply" in {
val actor = system.actorOf(Props[TestActor].withDispatcher("pinned-dispatcher"))
assert("World" === Await.result(actor ? "Hello", timeout.duration))
system.stop(actor)
}
}
}
示例2: DispatcherActorsSpec
//设置package包名称以及导入依赖的类
package akka.actor.dispatch
import java.util.concurrent.CountDownLatch
import akka.actor._
import akka.testkit.AkkaSpec
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class DispatcherActorsSpec extends AkkaSpec {
class SlowActor(finishedCounter: CountDownLatch) extends Actor {
def receive = {
case x: Int ? {
Thread.sleep(50) // slow actor
finishedCounter.countDown()
}
}
}
class FastActor(finishedCounter: CountDownLatch) extends Actor {
def receive = {
case x: Int ? {
finishedCounter.countDown()
}
}
}
"A dispatcher and two actors" must {
"not block fast actors by slow actors" in {
val sFinished = new CountDownLatch(50)
val fFinished = new CountDownLatch(10)
val s = system.actorOf(Props(new SlowActor(sFinished)))
val f = system.actorOf(Props(new FastActor(fFinished)))
// send a lot of stuff to s
for (i ? 1 to 50) {
s ! i
}
// send some messages to f
for (i ? 1 to 10) {
f ! i
}
// now assert that f is finished while s is still busy
fFinished.await
assert(sFinished.getCount > 0)
sFinished.await
assert(sFinished.getCount === 0)
system.stop(f)
system.stop(s)
}
}
}
示例3: TestLatch
//设置package包名称以及导入依赖的类
package akka.testkit
import scala.concurrent.duration.Duration
import akka.actor.ActorSystem
import scala.concurrent.{ Await, CanAwait, Awaitable }
import java.util.concurrent.{ TimeoutException, CountDownLatch, TimeUnit }
import scala.concurrent.duration.FiniteDuration
object TestLatch {
val DefaultTimeout = Duration(5, TimeUnit.SECONDS)
def apply(count: Int = 1)(implicit system: ActorSystem) = new TestLatch(count)
}
class TestLatch(count: Int = 1)(implicit system: ActorSystem) extends Awaitable[Unit] {
private var latch = new CountDownLatch(count)
def countDown() = latch.countDown()
def isOpen: Boolean = latch.getCount == 0
def open() = while (!isOpen) countDown()
def reset() = latch = new CountDownLatch(count)
@throws(classOf[TimeoutException])
def ready(atMost: Duration)(implicit permit: CanAwait) = {
val waitTime = atMost match {
case f: FiniteDuration ? f
case _ ? throw new IllegalArgumentException("TestLatch does not support waiting for " + atMost)
}
val opened = latch.await(waitTime.dilated.toNanos, TimeUnit.NANOSECONDS)
if (!opened) throw new TimeoutException(
"Timeout of %s with time factor of %s" format (atMost.toString, TestKitExtension(system).TestTimeFactor))
this
}
@throws(classOf[Exception])
def result(atMost: Duration)(implicit permit: CanAwait): Unit = {
ready(atMost)
}
}
示例4: ReqRealTimeBarsHandler
//设置package包名称以及导入依赖的类
package name.kaeding.fibs
package ib
package impl
package handlers
import java.util.concurrent.CountDownLatch
import scalaz._, Scalaz._
import scalaz.concurrent._
import messages._
import contract._
import java.util.concurrent.{ LinkedBlockingQueue, BlockingQueue }
import com.ib.client.EClientSocket
import com.github.nscala_time.time.Imports._
import grizzled.slf4j.Logging
class ReqRealTimeBarsHandler(security: Stock ,
ibActor: Actor[FibsPromiseMessage \/ IBMessage],
tickerId: Int, socket: EClientSocketLike) extends FibsPromise[CloseableStream[RealTimeBar]] with Logging {
private[this] val TickerId = tickerId
val latch = new CountDownLatch(0) // don't need to block
val actor = Actor[IBMessage] {
case RealTimeBarResp(TickerId, time, open, high, low, close, volume, count, wap) ?
queue.add(RealTimeBar(new DateTime(time * 1000), open, high, low, close, volume, count, wap).some)
case _ ? ???
}
val barHandler: PartialFunction[IBMessage, Unit] = {
case [email protected](TickerId, time, open, high, low, close, volume, count, wap) ? actor ! m
}
val patterns = List(barHandler)
private[this] def toStream: EphemeralStream[RealTimeBar] = {
val ret: EphemeralStream[RealTimeBar] = queue.take match {
case Some(d) ? EphemeralStream.cons(d, toStream)
case None ? EphemeralStream.emptyEphemeralStream
}
ret
}
private[this] val queue: BlockingQueue[Option[RealTimeBar]] =
new LinkedBlockingQueue[Option[RealTimeBar]]()
private[this] def closeStream = {
queue add None
socket.cancelRealTimeBars(tickerId)
ibActor ! UnregisterFibsPromise(this).left
}
def get = new CloseableStream[RealTimeBar] {
def close = closeStream
lazy val as = toStream
}
}
示例5: ReqHistoricalDataHandler
//设置package包名称以及导入依赖的类
package name.kaeding.fibs
package ib
package impl
package handlers
import java.util.concurrent.CountDownLatch
import java.util.concurrent.{ LinkedBlockingQueue, BlockingQueue }
import scalaz._, Scalaz._
import scalaz.concurrent._
import com.github.nscala_time.time.Imports._
import messages._
import contract._
class ReqHistoricalDataHandler(security: Stock ,
ibActor: Actor[FibsPromiseMessage \/ IBMessage],
tickerId: Int) extends FibsPromise[Stream[HistoricalDataPeriod]] {
private[this] val TickerId = tickerId
val actor = Actor[IBMessage]{
case d @ HistoricalData(TickerId, time, _, _, _, _, _, _, _, _) if (!time.startsWith("finished-")) =>
enqueue(transformMsg(d))
case d @ HistoricalData(TickerId, time, _, _, _, _, _, _, _, _) if (time.startsWith("finished-")) =>
close
case d @ HistoricalDataError(TickerId, 162, msg) if (msg contains "HMDS query returned no data") =>
close
case _ => ???
}
val historicalDataHandler: PartialFunction[IBMessage, Unit] = {
case d @ HistoricalData(TickerId, _, _, _, _, _, _, _, _, _) => actor ! d
case d @ HistoricalDataError(TickerId, 162, msg) if (msg contains "HMDS query returned no data") =>
actor ! d
}
val patterns = List(historicalDataHandler)
val latch = new CountDownLatch(0) // don't need to block
def get = toStream
private[this] def transformMsg(i: HistoricalData) =
HistoricalDataPeriod(
new DateTime(i.date.parseLong.toOption.getOrElse(0L) * 1000),
i.open,
i.high,
i.low,
i.close,
i.volume,
i.count,
i.wap,
i.hasGaps)
private[this] val queue: BlockingQueue[Option[HistoricalDataPeriod]] =
new LinkedBlockingQueue[Option[HistoricalDataPeriod]]()
private[this] def close = {
queue add None
ibActor ! UnregisterFibsPromise(this).left
}
private[this] def enqueue(d: HistoricalDataPeriod) = queue add d.some
private[this] def toStream(): Stream[HistoricalDataPeriod] = queue.take match {
case Some(d) => Stream.cons(d, toStream)
case None => Stream.empty
}
}
示例6: ReqMarketTickDataStreamHandler
//设置package包名称以及导入依赖的类
package name.kaeding.fibs
package ib
package impl
package handlers
import java.util.concurrent.CountDownLatch
import scalaz._, Scalaz._
import scalaz.concurrent._
import messages._
import contract._
import java.util.concurrent.{ LinkedBlockingQueue, BlockingQueue }
import com.ib.client.EClientSocket
import com.github.nscala_time.time.Imports._
import grizzled.slf4j.Logging
class ReqMarketTickDataStreamHandler(security: Stock ,
ibActor: Actor[FibsPromiseMessage \/ IBMessage],
tickerId: Int, socket: EClientSocketLike) extends FibsPromise[CloseableStream[MarketTickDataResult]] with Logging {
private[this] val TickerId = tickerId
val latch = new CountDownLatch(0) // don't need to block
private[this] val RTVolumePattern = "(\\d+\\.?\\d*);(\\d+);(\\d+);(\\d+);(\\d+\\.?\\d*);(true|false)".r
val actor = Actor[IBMessage] {
case TickString(TickerId, RTVolume, v) ?
parseInput(v).cata(some = t => queue.add(t.some),
none = warn(s"error parsing tick data: $v"))
case _ ? ???
}
def parseInput(s: String) = s match {
case RTVolumePattern(p, s, t, v, w, f) =>
(p.parseDouble.toOption |@|
s.parseInt.toOption |@|
v.parseInt.toOption |@|
t.parseLong.toOption |@|
w.parseDouble.toOption |@|
f.parseBoolean.toOption)(MarketTickDataResult.apply)
case _ => none
}
val stringHandler: PartialFunction[IBMessage, Unit] = {
case [email protected](tickerId, RTVolume, _) ? actor ! m
}
val patterns = List(stringHandler)
private[this] val queue: BlockingQueue[Option[MarketTickDataResult]] =
new LinkedBlockingQueue[Option[MarketTickDataResult]]()
private[this] def closeStream = {
queue add None
socket.cancelMktData(TickerId)
ibActor ! UnregisterFibsPromise(this).left
}
private[this] def toStream: EphemeralStream[MarketTickDataResult] = {
val ret: EphemeralStream[MarketTickDataResult] = queue.take match {
case Some(d) ? EphemeralStream.cons(d, toStream)
case None ? EphemeralStream.emptyEphemeralStream
}
ret
}
def get = new CloseableStream[MarketTickDataResult] {
def close = closeStream
lazy val as = toStream
}
}
示例7: Nonblocking
//设置package包名称以及导入依赖的类
package fpinscala.parallelism
import java.util.concurrent.{Callable, CountDownLatch, ExecutorService}
import java.util.concurrent.atomic.AtomicReference
import language.implicitConversions
object Nonblocking {
trait Future[+A] {
private[parallelism] def apply(k: A => Unit): Unit
}
type Par[+A] = ExecutorService => Future[A]
object Par {
def run[A](es: ExecutorService)(p: Par[A]): A = {
val ref = new java.util.concurrent.atomic.AtomicReference[A] // A mutable, threadsafe reference, to use for storing the result
val latch = new CountDownLatch(1) // A latch which, when decremented, implies that `ref` has the result
p(es) { a => ref.set(a); latch.countDown } // Asynchronously set the result, and decrement the latch
latch.await // Block until the `latch.countDown` is invoked asynchronously
ref.get // Once we've passed the latch, we know `ref` has been set, and return its value
}
def unit[A](a: A): Par[A] =
es => new Future[A] {
def apply(cb: A => Unit): Unit =
cb(a)
}
implicit def toParOps[A](p: Par[A]): ParOps[A] = new ParOps(p)
// infix versions of `map`, `map2`
class ParOps[A](p: Par[A]) {
def map[B](f: A => B): Par[B] = Par.map(p)(f)
def map2[B,C](b: Par[B])(f: (A,B) => C): Par[C] = Par.map2(p,b)(f)
def zip[B](b: Par[B]): Par[(A,B)] = p.map2(b)((_,_))
}
}
}
示例8: SchedulerSpec
//设置package包名称以及导入依赖的类
package knot.core.scheduler
import java.util.concurrent.{CountDownLatch, TimeUnit}
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class SchedulerSpec extends FunSpec {
val s = new Schedulers()
describe("scheduler") {
it("scheduler is singleton") {
s.single should be theSameInstanceAs s.single
}
it("singl scheduler") {
val cdl = new CountDownLatch(2)
val start = System.currentTimeMillis()
s.single.schedule(() => cdl.countDown(), 1, 1, TimeUnit.SECONDS)
cdl.await()
val end = System.currentTimeMillis()
end - start should be(2000L +- 100L)
}
it("singl scheduler / wait next command") {
val cdl = new CountDownLatch(4)
val start = System.currentTimeMillis()
s.single.schedule(() => {
Thread.sleep(1000) // heavy job
cdl.countDown()
}, 1, 1, TimeUnit.SECONDS)
s.single.schedule(() => cdl.countDown(), 1, 1, TimeUnit.SECONDS)
cdl.await()
val end = System.currentTimeMillis()
end - start should be(4000L +- 100L)
}
}
}
示例9: SubscribeSignalSpec
//设置package包名称以及导入依赖的类
package knot.core.emitters
import java.util.concurrent.{CountDownLatch, TimeUnit}
import knot.core.Signals.{Start, Subscribe}
import knot.core.Workbench
import knot.core.adapter.LocalAdapter
import knot.core.config.Configs
import knot.core.sources.IteratorSource
import knot.testKit.ThroughParser
import org.scalatest.{BeforeAndAfter, FunSpec}
class SubscribeSignalSpec extends FunSpec with BeforeAndAfter {
implicit val wb: Workbench = Workbench.on("test")
var ctl = new CountDownLatch(1)
private def getTestEmitter: (LocalAdapter, LocalAdapter) = {
val s = PublishEmitter[Int](wb, Configs.defaultPartConfig, IteratorSource(0 until 1))
val p = ProcessEmitter[Int, Int](wb, Configs.defaultPartConfig, ThroughParser[Int](_ => ctl.countDown()))
(LocalAdapter(s), LocalAdapter(p))
}
before {
ctl = new CountDownLatch(1)
}
describe("subscribe signal") {
it("source subscribe -> start") {
val te = getTestEmitter
te._1.send(Subscribe(te._2))
Thread.sleep(100)
te._1.send(Start)
ctl.await(10, TimeUnit.SECONDS)
}
it("source start -> subscribe") {
val te = getTestEmitter
te._1.send(Start)
Thread.sleep(100)
te._1.send(Subscribe(te._2))
ctl.await(10, TimeUnit.SECONDS)
}
it("parser start -> subscribe") {
val te = getTestEmitter
te._1.send(Start)
te._2.send(Start)
Thread.sleep(100)
te._1.send(Subscribe(te._2))
ctl.await(10, TimeUnit.SECONDS)
}
}
}
示例10: withFixture
//设置package包名称以及导入依赖的类
package io.scalatestfx.zzznolongerused
import java.util.concurrent.CountDownLatch
import javafx.application.Platform
import org.scalatest.{Outcome, TestSuite, TestSuiteMixin}
trait RunOnApplicationThread extends TestSuiteMixin {
this: TestSuite =>
abstract override def withFixture(test: NoArgTest): Outcome = {
BootstrapApplication.launch()
val appThreadLatch = new CountDownLatch(1)
val superWith = super.withFixture _ // required to access to super withFixture method from within runnable for a trait
var testException: Exception = null
var outcome: Outcome = null
Platform.runLater(new Runnable() {
override def run() {
try {
outcome = superWith(test)
} catch {
case e: Exception => testException = e
} finally {
appThreadLatch.countDown()
}
}
})
appThreadLatch.await()
if (testException != null) {
throw testException
}
outcome
}
}
示例11: BootstrapApplication
//设置package包名称以及导入依赖的类
package io.scalatestfx.zzznolongerused
import java.util.concurrent.CountDownLatch
import javafx.application.Application
import javafx.stage.Stage
object BootstrapApplication {
private val launchLatch = new CountDownLatch(1)
var launched = false
def launch() {
if (!launched) {
new Thread(new Runnable() {
def run() {
Application.launch(classOf[BootstrapApplication])
}
}).start()
launchLatch.await()
launched = true
}
}
}
class BootstrapApplication extends Application {
override def start(stage: Stage) {
BootstrapApplication.launchLatch.countDown()
}
}
示例12: SyncManagerTest
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.tests.sync
import java.util.concurrent.{CountDownLatch, TimeUnit}
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.sync.SyncType.SyncType
import com.flipkart.connekt.commons.sync.{SyncDelegate, SyncManager, SyncMessage, SyncType}
import com.flipkart.connekt.commons.tests.ConnektUTSpec
class SyncManagerTest extends ConnektUTSpec with SyncDelegate {
"Sync operation" should "sync" in {
SyncManager.create("127.0.0.1:2181")
//Subscribe to the NF
SyncManager.get().addObserver(this, List(SyncType.TEMPLATE_CHANGE))
SyncManager.get().publish(SyncMessage(SyncType.TEMPLATE_CHANGE, List("Hello via Curator", "Hello via Zookeeper" + System.currentTimeMillis())))
noException should be thrownBy SyncTestVariables.lock.await(120, TimeUnit.SECONDS)
assert(null != SyncTestVariables.receivedData )
}
override def onUpdate(_type: SyncType, args: List[AnyRef]): Any = {
ConnektLogger(LogFile.SERVICE).info("Recieved Async [" + _type + "] with data " + args)
SyncTestVariables.receivedData = args
SyncTestVariables.lock.countDown()
}
}
object SyncTestVariables {
val lock = new CountDownLatch(1)
var receivedData: Any = null
}
示例13: ChanTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.util
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import java.util.concurrent.CyclicBarrier
import scala.collection.mutable.Buffer
import java.util.concurrent.CountDownLatch
@RunWith(classOf[JUnitRunner])
class ChanTest extends FunSuite {
test("Proc should admit one at a time, in the order received, queueing items") {
val threads = Buffer[Thread]()
val l = new CountDownLatch(1)
val b = new CyclicBarrier(2)
val p = Proc[Thread] { t => threads += t; l.countDown(); b.await() }
val t0 = new Thread {
override def run() {
p ! this
}
}
val t1 = new Thread {
override def run() {
l.await()
p ! this
b.await()
b.await()
}
}
t0.start();
t1.start()
t0.join();
t1.join()
assert(threads.toSeq == Seq(t0, t1))
}
test("Proc should swallow exceptions") {
val p = Proc[Int] { _ => throw new RuntimeException }
assert((p ! 4) ===((): Unit))
}
}
示例14: UpdaterTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.util
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import java.util.concurrent.{CyclicBarrier, CountDownLatch}
@RunWith(classOf[JUnitRunner])
class UpdaterTest extends FunSuite {
test("Prioritization") {
case class Work(p: Int)
@volatile var worked: Seq[Work] = Nil
val barrier = new CyclicBarrier(2)
val first = new CountDownLatch(1)
val u = new Updater[Work] {
protected def preprocess(elems: Seq[Work]) =
Seq(elems.minBy(_.p))
def handle(w: Work) {
worked :+= w
first.countDown()
barrier.await()
()
}
}
val w0 = Work(0)
val thr = new Thread("Test-Updater") {
override def run() {
u(w0)
}
}
thr.start()
first.await()
assert(worked == Seq(Work(0)))
u(Work(3))
u(Work(10))
u(Work(1))
u(Work(3))
barrier.await()
barrier.await()
thr.join()
assert(worked == Seq(Work(0), Work(1)))
}
}
示例15: Yolo
//设置package包名称以及导入依赖的类
package eveapi
import eveapi.oauth._
import OAuth2._
import scalaz._, Scalaz._
import scalaz.concurrent.Task
import eveapi.errors._
import org.http4s._, org.http4s.dsl._
import org.http4s.server.Server
import org.http4s.server.blaze._
import org.atnos.eff._, org.atnos.eff.syntax.all._, org.atnos.eff.all._
import java.time.Clock
import java.util.concurrent.CountDownLatch
case class Yolo(oauth: OAuth2, token: OAuth2Token) {
def run[T](api: Api[T]): T = Yolo.deeff(api).run((oauth, token)).unsafePerformSync.leftMap(err => throw err).merge
def run[T](free: Free[Lift.Link, T]): T = Yolo.deeff(free.foldMap(Execute.OAuthInterpreter)).run((oauth, token)).unsafePerformSync.leftMap(err => throw err).merge
}
object Yolo {
def deeff[T](api: Api[T]): Reader[(OAuth2, OAuth2Token), Task[\/[EveApiError, T]]] =
Reader({case (oauth, token) =>
Eff.detach[Task, \/[EveApiError, T]](api.runReader[OAuth2](oauth).runState(token).map(_._1).runDisjunction)
})
val client = org.http4s.client.blaze.PooledHttp1Client()
val seed = new java.security.SecureRandom().nextLong
val clock = Clock.systemUTC()
def oauth2(callback: Uri, clientId: String, clientSecret: String, scope: String): OAuth2 = OAuth2(client,
OAuth2Settings(
Uri.uri("https://login.eveonline.com/oauth/authorize"),
Uri.uri("https://login.eveonline.com/oauth/token"),
callback,
Uri.uri("https://login.eveonline.com/oauth/verify"),
clientId,
clientSecret,
Uri.uri("https://login.eveonline.com/oauth/token"),
Some(scope)
), OAuth2State(seed), clock, OAuth2ClientSettings("login"))
// Thanks to @rossabaker
def genToken(oauth: OAuth2): Task[Yolo] =
Task.async[Yolo]({ k =>
val latch = new CountDownLatch(1)
val service = oauth.oauthService({
token => k(\/-(Yolo(oauth, token))); Ok("Done.").map({x =>latch.countDown(); x})
})
val port = oauth.settings.callbackUri.port.getOrElse(80)
val server: Server = BlazeBuilder.mountService(Kleisli(service).local({x => println(x); x})).bindHttp(port, "localhost").run
println(s"Go to http://localhost:${port}/login")
latch.await()
server.shutdown.unsafePerformSync
})
}