Skip to content

Instantly share code, notes, and snippets.

@olafurpg
Created July 17, 2017 11:15
Show Gist options
  • Save olafurpg/82b6fa8261ba2f1dc147dccd595098ab to your computer and use it in GitHub Desktop.
Save olafurpg/82b6fa8261ba2f1dc147dccd595098ab to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala
index 8b216ab..73702c4 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala
@@ -15,7 +15,7 @@ import com.typesafe.config.ConfigFactory
object ActorCreationPerfSpec {
- val config = ConfigFactory.parseString("""
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.test.actor.ActorPerfSpec {
warmUp = 5
numberOfActors = 10
@@ -40,29 +40,29 @@ object ActorCreationPerfSpec {
case object Waited
class EmptyActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case IsAlive ⇒ sender() ! Alive
}
}
class EmptyArgsActor(val foo: Int, val bar: Int) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case IsAlive ⇒ sender() ! Alive
}
}
class TimingDriver(hist: Histogram) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case IsAlive ⇒
sender() ! Alive
case Create(number, propsCreator) ⇒
for (i ← 1 to number) {
- val start = System.nanoTime()
+ val start: Long = System.nanoTime()
context.actorOf(propsCreator.apply())
// yes, we are aware of this being skewed
- val stop = System.nanoTime()
+ val stop: Long = System.nanoTime()
hist.update(stop - start)
}
@@ -88,7 +88,7 @@ object ActorCreationPerfSpec {
class Driver extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case IsAlive ⇒
sender() ! Alive
case Create(number, propsCreator) ⇒
@@ -121,21 +121,21 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with
import ActorCreationPerfSpec._
- def metricsConfig = system.settings.config
- val ActorCreationKey = MetricKey.fromString("actor-creation")
- val BlockingTimeKey = ActorCreationKey / "synchronous-part"
- val TotalTimeKey = ActorCreationKey / "total"
+ def metricsConfig: com.typesafe.config.Config = system.settings.config
+ val ActorCreationKey: ActorCreationPerfSpec.this.MetricKey = MetricKey.fromString("actor-creation")
+ val BlockingTimeKey: ActorCreationPerfSpec.this.MetricKey = ActorCreationKey / "synchronous-part"
+ val TotalTimeKey: ActorCreationPerfSpec.this.MetricKey = ActorCreationKey / "total"
- val warmUp = metricsConfig.getInt("akka.test.actor.ActorPerfSpec.warmUp")
- val nrOfActors = metricsConfig.getInt("akka.test.actor.ActorPerfSpec.numberOfActors")
- val nrOfRepeats = metricsConfig.getInt("akka.test.actor.ActorPerfSpec.numberOfRepeats")
- override val reportMetricsEnabled = metricsConfig.getBoolean("akka.test.actor.ActorPerfSpec.report-metrics")
- override val forceGcEnabled = metricsConfig.getBoolean("akka.test.actor.ActorPerfSpec.force-gc")
+ val warmUp: Int = metricsConfig.getInt("akka.test.actor.ActorPerfSpec.warmUp")
+ val nrOfActors: Int = metricsConfig.getInt("akka.test.actor.ActorPerfSpec.numberOfActors")
+ val nrOfRepeats: Int = metricsConfig.getInt("akka.test.actor.ActorPerfSpec.numberOfRepeats")
+ override val reportMetricsEnabled: Boolean = metricsConfig.getBoolean("akka.test.actor.ActorPerfSpec.report-metrics")
+ override val forceGcEnabled: Boolean = metricsConfig.getBoolean("akka.test.actor.ActorPerfSpec.force-gc")
def runWithCounterInside(metricName: String, scenarioName: String, number: Int, propsCreator: () ⇒ Props) {
- val hist = histogram(BlockingTimeKey / metricName)
+ val hist: com.codahale.metrics.Histogram = histogram(BlockingTimeKey / metricName)
- val driver = system.actorOf(Props(classOf[TimingDriver], hist), scenarioName)
+ val driver: akka.actor.ActorRef = system.actorOf(Props(classOf[TimingDriver], hist), scenarioName)
driver ! IsAlive
expectMsg(Alive)
@@ -152,14 +152,14 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with
}
def runWithoutCounter(scenarioName: String, number: Int, propsCreator: () ⇒ Props): HeapMemoryUsage = {
- val mem = measureMemory(TotalTimeKey / scenarioName)
+ val mem: com.codahale.metrics.jvm.MemoryUsageGaugeSet with akka.testkit.metrics.MemoryUsageSnapshotting = measureMemory(TotalTimeKey / scenarioName)
- val driver = system.actorOf(Props(classOf[Driver]), scenarioName)
+ val driver: akka.actor.ActorRef = system.actorOf(Props(classOf[Driver]), scenarioName)
driver ! IsAlive
expectMsg(Alive)
gc()
- val before = mem.getHeapSnapshot
+ val before: akka.testkit.metrics.HeapMemoryUsage = mem.getHeapSnapshot
driver ! Create(number, propsCreator)
expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created ⇒ }
@@ -168,7 +168,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with
expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited ⇒ }
gc()
- val after = mem.getHeapSnapshot
+ val after: akka.testkit.metrics.HeapMemoryUsage = mem.getHeapSnapshot
driver ! PoisonPill
watch(driver)
@@ -178,7 +178,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with
}
def registerTests(name: String, propsCreator: () ⇒ Props) {
- val scenarioName = name.replaceAll("""[^\w]""", "")
+ val scenarioName: String = name.replaceAll("""[^\w]""", "")
s"warm-up before: $name" taggedAs PerformanceTest in {
if (warmUp > 0) {
@@ -199,10 +199,10 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with
}
s"measure total creation time for $name" taggedAs PerformanceTest in {
- val avgMem = averageGauge(ActorCreationKey / name / "avg-mem-per-actor")
+ val avgMem: akka.testkit.metrics.AveragingGauge = averageGauge(ActorCreationKey / name / "avg-mem-per-actor")
for (i ← 1 to nrOfRepeats) {
- val heapUsed = timedWithKnownOps(TotalTimeKey / s"creating-$nrOfActors-actors" / name, ops = nrOfActors) {
+ val heapUsed: akka.testkit.metrics.HeapMemoryUsage = timedWithKnownOps(TotalTimeKey / s"creating-$nrOfActors-actors" / name, ops = nrOfActors) {
runWithoutCounter(s"${scenarioName}_driver_outside_$i", nrOfActors, propsCreator)
}
@@ -218,26 +218,26 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with
registerTests("Props[EmptyActor] with new Props", () ⇒ Props[EmptyActor])
- val props1 = Props[EmptyActor]
+ val props1: akka.actor.Props = Props[EmptyActor]
registerTests("Props[EmptyActor] with same Props", () ⇒ props1)
registerTests("Props(new EmptyActor) new", () ⇒ { Props(new EmptyActor) })
- val props2 = Props(new EmptyActor)
+ val props2: akka.actor.Props = Props(new EmptyActor)
registerTests("Props(new EmptyActor) same", () ⇒ { props2 })
registerTests("Props(classOf[EmptyArgsActor], ...) new", () ⇒ { Props(classOf[EmptyArgsActor], 4711, 1729) })
- val props3 = Props(classOf[EmptyArgsActor], 4711, 1729)
+ val props3: akka.actor.Props = Props(classOf[EmptyArgsActor], 4711, 1729)
registerTests("Props(classOf[EmptyArgsActor], ...) same", () ⇒ { props3 })
registerTests("Props(new EmptyArgsActor(...)) new", () ⇒ { Props(new EmptyArgsActor(4711, 1729)) })
- val props4 = Props(new EmptyArgsActor(4711, 1729))
+ val props4: akka.actor.Props = Props(new EmptyArgsActor(4711, 1729))
registerTests("Props(new EmptyArgsActor(...)) same", () ⇒ { props4 })
}
- override def afterTermination() = shutdownMetrics()
+ override def afterTermination(): Unit = shutdownMetrics()
- override def expectedTestDuration = 5 minutes
+ override def expectedTestDuration: scala.concurrent.duration.FiniteDuration = 5 minutes
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala
index c6a6b63..5b54308 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala
@@ -19,14 +19,14 @@ class ActorDSLDummy {
import akka.actor.ActorDSL._
import akka.actor.ActorSystem
- implicit val system = ActorSystem("demo")
+ implicit val system: akka.actor.ActorSystem = ActorSystem("demo")
//#import
}
class ActorDSLSpec extends AkkaSpec {
- val echo = system.actorOf(Props(new Actor {
- def receive = {
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case x ⇒ sender() ! x
}
}))
@@ -35,7 +35,7 @@ class ActorDSLSpec extends AkkaSpec {
"function as implicit sender" in {
//#inbox
- implicit val i = inbox()
+ implicit val i: akka.actor.ActorDSL.Inbox = inbox()
echo ! "hello"
i.receive() should ===("hello")
//#inbox
@@ -44,10 +44,10 @@ class ActorDSLSpec extends AkkaSpec {
"support watch" in {
//#watch
val target = // some actor
- //#watch
+ //#watch: akka.actor.ActorRef
actor(new Act {})
//#watch
- val i = inbox()
+ val i: akka.actor.ActorDSL.Inbox = inbox()
i watch target
//#watch
target ! PoisonPill
@@ -55,9 +55,9 @@ class ActorDSLSpec extends AkkaSpec {
}
"support queueing multiple queries" in {
- val i = inbox()
+ val i: akka.actor.ActorDSL.Inbox = inbox()
import system.dispatcher
- val res = Future.sequence(Seq(
+ val res: scala.concurrent.Future[Seq[Any]] = Future.sequence(Seq(
Future { i.receive() } recover { case x ⇒ x },
Future { Thread.sleep(100); i.select() { case "world" ⇒ 1 } } recover { case x ⇒ x },
Future { Thread.sleep(200); i.select() { case "hello" ⇒ 2 } } recover { case x ⇒ x }))
@@ -70,10 +70,10 @@ class ActorDSLSpec extends AkkaSpec {
}
"support selective receives" in {
- val i = inbox()
+ val i: akka.actor.ActorDSL.Inbox = inbox()
i.receiver ! "hello"
i.receiver ! "world"
- val result = i.select() {
+ val result: Boolean = i.select() {
case "world" ⇒ true
}
result should ===(true)
@@ -81,7 +81,7 @@ class ActorDSLSpec extends AkkaSpec {
}
"have a maximum queue size" taggedAs TimingTest in {
- val i = inbox()
+ val i: akka.actor.ActorDSL.Inbox = inbox()
system.eventStream.subscribe(testActor, classOf[Warning])
try {
for (_ ← 1 to 1000) i.receiver ! 0
@@ -92,7 +92,7 @@ class ActorDSLSpec extends AkkaSpec {
expectMsgType[Warning]
i.receiver ! 42
expectNoMsg(1 second)
- val gotit = for (_ ← 1 to 1000) yield i.receive()
+ val gotit: scala.collection.immutable.IndexedSeq[Any] = for (_ ← 1 to 1000) yield i.receive()
gotit should ===((1 to 1000) map (_ ⇒ 0))
intercept[TimeoutException] {
i.receive(1 second)
@@ -103,7 +103,7 @@ class ActorDSLSpec extends AkkaSpec {
}
"have a default and custom timeouts" taggedAs TimingTest in {
- val i = inbox()
+ val i: akka.actor.ActorDSL.Inbox = inbox()
within(5 seconds, 6 seconds) {
intercept[TimeoutException](i.receive())
}
@@ -118,21 +118,21 @@ class ActorDSLSpec extends AkkaSpec {
"support creating regular actors" in {
//#simple-actor
- val a = actor(new Act {
+ val a: akka.actor.ActorRef = actor(new Act {
become {
case "hello" ⇒ sender() ! "hi"
}
})
//#simple-actor
- implicit val i = inbox()
+ implicit val i: akka.actor.ActorDSL.Inbox = inbox()
a ! "hello"
i.receive() should ===("hi")
}
"support becomeStacked" in {
//#becomeStacked
- val a = actor(new Act {
+ val a: akka.actor.ActorRef = actor(new Act {
become { // this will replace the initial (empty) behavior
case "info" ⇒ sender() ! "A"
case "switch" ⇒
@@ -145,7 +145,7 @@ class ActorDSLSpec extends AkkaSpec {
})
//#becomeStacked
- implicit val sender = testActor
+ implicit val sender: akka.actor.ActorRef = testActor
a ! "info"
expectMsg("A")
a ! "switch"
@@ -158,7 +158,7 @@ class ActorDSLSpec extends AkkaSpec {
"support setup/teardown" in {
//#simple-start-stop
- val a = actor(new Act {
+ val a: akka.actor.ActorRef = actor(new Act {
whenStarting { testActor ! "started" }
whenStopping { testActor ! "stopped" }
})
@@ -171,7 +171,7 @@ class ActorDSLSpec extends AkkaSpec {
"support restart" in {
//#failing-actor
- val a = actor(new Act {
+ val a: akka.actor.ActorRef = actor(new Act {
become {
case "die" ⇒ throw new Exception
}
@@ -188,7 +188,7 @@ class ActorDSLSpec extends AkkaSpec {
}
"support superviseWith" in {
- val a = actor(new Act {
+ val a: akka.actor.ActorRef = actor(new Act {
val system = null // shadow the implicit system
//#supervise-with
superviseWith(OneForOneStrategy() {
@@ -196,7 +196,7 @@ class ActorDSLSpec extends AkkaSpec {
case _: Exception ⇒ Resume
})
//#supervise-with
- val child = actor("child")(new Act {
+ val child: akka.actor.ActorRef = actor("child")(new Act {
whenFailing { (_, _) ⇒ }
become {
case ref: ActorRef ⇒ whenStopping(ref ! "stopped")
@@ -219,11 +219,11 @@ class ActorDSLSpec extends AkkaSpec {
}
"supported nested declaration" in {
- val system = this.system
+ val system: akka.actor.ActorSystem = this.system
//#nested-actor
// here we pass in the ActorRefFactory explicitly as an example
- val a = actor(system, "fred")(new Act {
- val b = actor("barney")(new Act {
+ val a: akka.actor.ActorRef = actor(system, "fred")(new Act {
+ val b: akka.actor.ActorRef = actor("barney")(new Act {
whenStarting { context.parent ! ("hello from " + self.path) }
})
become {
@@ -237,7 +237,7 @@ class ActorDSLSpec extends AkkaSpec {
"support Stash" in {
//#act-with-stash
- val a = actor(new ActWithStash {
+ val a: akka.actor.ActorRef = actor(new ActWithStash {
become {
case 1 ⇒ stash()
case 2 ⇒
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala
index 48ddabe..8a9b077 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala
@@ -19,12 +19,12 @@ import java.util.UUID.{ randomUUID ⇒ newUuid }
object ActorLifeCycleSpec {
class LifeCycleTestActor(testActor: ActorRef, id: String, generationProvider: AtomicInteger) extends Actor {
- def report(msg: Any) = testActor ! message(msg)
+ def report(msg: Any): Unit = testActor ! message(msg)
def message(msg: Any): Tuple3[Any, String, Int] = (msg, id, currentGen)
- val currentGen = generationProvider.getAndIncrement()
+ val currentGen: Int = generationProvider.getAndIncrement()
override def preStart() { report("preStart") }
override def postStop() { report("postStop") }
- def receive = { case "status" ⇒ sender() ! message("OK") }
+ def receive: PartialFunction[Any, Unit] = { case "status" ⇒ sender() ! message("OK") }
}
}
@@ -36,14 +36,14 @@ class ActorLifeCycleSpec extends AkkaSpec("akka.actor.serialize-messages=off") w
"invoke preRestart, preStart, postRestart when using OneForOneStrategy" in {
filterException[ActorKilledException] {
- val id = newUuid.toString
- val supervisor = system.actorOf(Props(classOf[Supervisor], OneForOneStrategy(maxNrOfRetries = 3)(List(classOf[Exception]))))
- val gen = new AtomicInteger(0)
- val restarterProps = Props(new LifeCycleTestActor(testActor, id, gen) {
+ val id: String = newUuid.toString
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(classOf[Supervisor], OneForOneStrategy(maxNrOfRetries = 3)(List(classOf[Exception]))))
+ val gen: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val restarterProps: akka.actor.Props = Props(new LifeCycleTestActor(testActor, id, gen) {
override def preRestart(reason: Throwable, message: Option[Any]) { report("preRestart") }
override def postRestart(reason: Throwable) { report("postRestart") }
}).withDeploy(Deploy.local)
- val restarter = Await.result((supervisor ? restarterProps).mapTo[ActorRef], timeout.duration)
+ val restarter: akka.actor.ActorRef = Await.result((supervisor ? restarterProps).mapTo[ActorRef], timeout.duration)
expectMsg(("preStart", id, 0))
restarter ! Kill
@@ -70,11 +70,11 @@ class ActorLifeCycleSpec extends AkkaSpec("akka.actor.serialize-messages=off") w
"default for preRestart and postRestart is to call postStop and preStart respectively" in {
filterException[ActorKilledException] {
- val id = newUuid().toString
- val supervisor = system.actorOf(Props(classOf[Supervisor], OneForOneStrategy(maxNrOfRetries = 3)(List(classOf[Exception]))))
- val gen = new AtomicInteger(0)
- val restarterProps = Props(classOf[LifeCycleTestActor], testActor, id, gen)
- val restarter = Await.result((supervisor ? restarterProps).mapTo[ActorRef], timeout.duration)
+ val id: String = newUuid().toString
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(classOf[Supervisor], OneForOneStrategy(maxNrOfRetries = 3)(List(classOf[Exception]))))
+ val gen: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val restarterProps: akka.actor.Props = Props(classOf[LifeCycleTestActor], testActor, id, gen)
+ val restarter: akka.actor.ActorRef = Await.result((supervisor ? restarterProps).mapTo[ActorRef], timeout.duration)
expectMsg(("preStart", id, 0))
restarter ! Kill
@@ -100,13 +100,13 @@ class ActorLifeCycleSpec extends AkkaSpec("akka.actor.serialize-messages=off") w
}
"not invoke preRestart and postRestart when never restarted using OneForOneStrategy" in {
- val id = newUuid().toString
- val supervisor = system.actorOf(Props(
+ val id: String = newUuid().toString
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(
classOf[Supervisor],
OneForOneStrategy(maxNrOfRetries = 3)(List(classOf[Exception]))))
- val gen = new AtomicInteger(0)
- val props = Props(classOf[LifeCycleTestActor], testActor, id, gen)
- val a = Await.result((supervisor ? props).mapTo[ActorRef], timeout.duration)
+ val gen: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val props: akka.actor.Props = Props(classOf[LifeCycleTestActor], testActor, id, gen)
+ val a: akka.actor.ActorRef = Await.result((supervisor ? props).mapTo[ActorRef], timeout.duration)
expectMsg(("preStart", id, 0))
a ! "status"
expectMsg(("OK", id, 0))
@@ -117,8 +117,8 @@ class ActorLifeCycleSpec extends AkkaSpec("akka.actor.serialize-messages=off") w
}
"log failues in postStop" in {
- val a = system.actorOf(Props(new Actor {
- def receive = Actor.emptyBehavior
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
override def postStop { throw new Exception("hurrah") }
}))
EventFilter[Exception]("hurrah", occurrences = 1) intercept {
@@ -128,8 +128,8 @@ class ActorLifeCycleSpec extends AkkaSpec("akka.actor.serialize-messages=off") w
"clear the behavior stack upon restart" in {
final case class Become(recv: ActorContext ⇒ Receive)
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Become(beh) ⇒ { context.become(beh(context), discardOld = false); sender() ! "ok" }
case x ⇒ sender() ! 42
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala
index 15dedaf..34e14dd 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala
@@ -20,10 +20,10 @@ object ActorLookupSpec {
final case class LookupPath(path: ActorPath) extends Query
final case class GetSender(to: ActorRef) extends Query
- val p = Props[Node]
+ val p: akka.actor.Props = Props[Node]
class Node extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Create(name) ⇒ sender() ! context.actorOf(p, name)
case LookupElems(path) ⇒ sender() ! context.actorFor(path)
case LookupString(path) ⇒ sender() ! context.actorFor(path)
@@ -37,17 +37,17 @@ object ActorLookupSpec {
class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
import ActorLookupSpec._
- val c1 = system.actorOf(p, "c1")
- val c2 = system.actorOf(p, "c2")
- val c21 = Await.result((c2 ? Create("c21")).mapTo[ActorRef], timeout.duration)
+ val c1: akka.actor.ActorRef = system.actorOf(p, "c1")
+ val c2: akka.actor.ActorRef = system.actorOf(p, "c2")
+ val c21: akka.actor.ActorRef = Await.result((c2 ? Create("c21")).mapTo[ActorRef], timeout.duration)
- val sysImpl = system.asInstanceOf[ActorSystemImpl]
+ val sysImpl: akka.actor.ActorSystemImpl = system.asInstanceOf[ActorSystemImpl]
- val user = sysImpl.guardian
- val syst = sysImpl.systemGuardian
- val root = sysImpl.lookupRoot
+ val user: akka.actor.LocalActorRef = sysImpl.guardian
+ val syst: akka.actor.LocalActorRef = sysImpl.systemGuardian
+ val root: akka.actor.InternalActorRef = sysImpl.lookupRoot
- def empty(path: String) =
+ def empty(path: String): akka.actor.EmptyLocalActorRef =
new EmptyLocalActorRef(sysImpl.provider, path match {
case RelativeActorPath(elems) ⇒ system.actorFor("/").path / elems
}, system.eventStream)
@@ -77,7 +77,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
"take actor incarnation into account when comparing actor references" in {
val name = "abcdefg"
- val a1 = system.actorOf(p, name)
+ val a1: akka.actor.ActorRef = system.actorOf(p, name)
watch(a1)
a1 ! PoisonPill
expectTerminated(a1)
@@ -88,7 +88,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
// not equal because it's terminated
system.actorFor(a1.path.toString) should not be (a1)
- val a2 = system.actorOf(p, name)
+ val a2: akka.actor.ActorRef = system.actorOf(p, name)
a2.path should ===(a1.path)
a2.path.toString should ===(a1.path.toString)
a2 should not be (a1)
@@ -136,7 +136,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
}
"return deadLetters or EmptyLocalActorRef, respectively, for non-existing paths" in {
- def check(lookup: ActorRef, result: ActorRef) = {
+ def check(lookup: ActorRef, result: ActorRef): org.scalatest.Assertion = {
lookup.getClass should ===(result.getClass)
lookup should ===(result)
}
@@ -150,8 +150,8 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
}
"find temporary actors" in {
- val f = c1 ? GetSender(testActor)
- val a = expectMsgType[ActorRef]
+ val f: scala.concurrent.Future[Any] = c1 ? GetSender(testActor)
+ val a: akka.actor.ActorRef = expectMsgType[ActorRef]
a.path.elements.head should ===("temp")
system.actorFor(a.path) should ===(a)
system.actorFor(a.path.toString) should ===(a)
@@ -171,7 +171,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
"An ActorContext" must {
- val all = Seq(c1, c2, c21)
+ val all: Seq[akka.actor.ActorRef] = Seq(c1, c2, c21)
"find actors by looking up their path" in {
def check(looker: ActorRef, pathOf: ActorRef, result: ActorRef) {
@@ -241,12 +241,12 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
import scala.collection.JavaConverters._
def checkOne(looker: ActorRef, query: Query, result: ActorRef) {
- val lookup = Await.result(looker ? query, timeout.duration)
+ val lookup: Any = Await.result(looker ? query, timeout.duration)
lookup.getClass should be(result.getClass)
lookup should ===(result)
}
def check(looker: ActorRef) {
- val lookname = looker.path.elements.mkString("", "/", "/")
+ val lookname: String = looker.path.elements.mkString("", "/", "/")
for (
(l, r) ← Seq(
LookupString("a/b/c") → empty(lookname + "a/b/c"),
@@ -263,8 +263,8 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
}
"find temporary actors" in {
- val f = c1 ? GetSender(testActor)
- val a = expectMsgType[ActorRef]
+ val f: scala.concurrent.Future[Any] = c1 ? GetSender(testActor)
+ val a: akka.actor.ActorRef = expectMsgType[ActorRef]
a.path.elements.head should ===("temp")
Await.result(c2 ? LookupPath(a.path), timeout.duration) should ===(a)
Await.result(c2 ? LookupString(a.path.toString), timeout.duration) should ===(a)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala
index 915aa81..b6dc206 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala
@@ -13,7 +13,7 @@ import com.typesafe.config.Config
import akka.util.Helpers.ConfigOps
object ActorMailboxSpec {
- val mailboxConf = ConfigFactory.parseString(s"""
+ val mailboxConf: com.typesafe.config.Config = ConfigFactory.parseString(s"""
unbounded-dispatcher {
mailbox-type = "akka.dispatch.UnboundedMailbox"
}
@@ -167,7 +167,7 @@ object ActorMailboxSpec {
""")
class QueueReportingActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case _ ⇒ sender() ! context.asInstanceOf[ActorCell].mailbox.messageQueue
}
}
@@ -184,24 +184,24 @@ object ActorMailboxSpec {
class StashQueueReportingActorWithParams(i: Int, s: String) extends StashQueueReportingActor
- val UnboundedMailboxTypes = Seq(classOf[UnboundedMessageQueueSemantics])
- val BoundedMailboxTypes = Seq(classOf[BoundedMessageQueueSemantics])
+ val UnboundedMailboxTypes: Seq[Class[akka.dispatch.UnboundedMessageQueueSemantics]] = Seq(classOf[UnboundedMessageQueueSemantics])
+ val BoundedMailboxTypes: Seq[Class[akka.dispatch.BoundedMessageQueueSemantics]] = Seq(classOf[BoundedMessageQueueSemantics])
- val UnboundedDeqMailboxTypes = Seq(
+ val UnboundedDeqMailboxTypes: Seq[Class[_ >: akka.dispatch.UnboundedDequeBasedMessageQueueSemantics <: Object]] = Seq(
classOf[DequeBasedMessageQueueSemantics],
classOf[UnboundedMessageQueueSemantics],
classOf[UnboundedDequeBasedMessageQueueSemantics])
- val BoundedDeqMailboxTypes = Seq(
+ val BoundedDeqMailboxTypes: Seq[Class[_ >: akka.dispatch.BoundedDequeBasedMessageQueueSemantics <: Object]] = Seq(
classOf[DequeBasedMessageQueueSemantics],
classOf[BoundedMessageQueueSemantics],
classOf[BoundedDequeBasedMessageQueueSemantics])
- val BoundedControlAwareMailboxTypes = Seq(
+ val BoundedControlAwareMailboxTypes: Seq[Class[_ >: akka.dispatch.BoundedControlAwareMessageQueueSemantics <: Object]] = Seq(
classOf[BoundedMessageQueueSemantics],
classOf[ControlAwareMessageQueueSemantics],
classOf[BoundedControlAwareMessageQueueSemantics])
- val UnboundedControlAwareMailboxTypes = Seq(
+ val UnboundedControlAwareMailboxTypes: Seq[Class[_ >: akka.dispatch.UnboundedControlAwareMessageQueueSemantics <: Object]] = Seq(
classOf[UnboundedMessageQueueSemantics],
classOf[ControlAwareMessageQueueSemantics],
classOf[UnboundedControlAwareMessageQueueSemantics])
@@ -227,10 +227,10 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
def this() = this(ActorMailboxSpec.mailboxConf)
def checkMailboxQueue(props: Props, name: String, types: Seq[Class[_]]): MessageQueue = {
- val actor = system.actorOf(props, name)
+ val actor: akka.actor.ActorRef = system.actorOf(props, name)
actor ! "ping"
- val q = expectMsgType[MessageQueue]
+ val q: akka.dispatch.MessageQueue = expectMsgType[MessageQueue]
types foreach (t ⇒ assert(t isInstance q, s"Type [${q.getClass.getName}] is not assignable to [${t.getName}]"))
q
}
@@ -317,7 +317,7 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
}
"get a bounded message queue with 0 push timeout when defined in dispatcher" in {
- val q = checkMailboxQueue(Props[QueueReportingActor], "default-bounded-mailbox-with-zero-pushtimeout", BoundedMailboxTypes)
+ val q: akka.dispatch.MessageQueue = checkMailboxQueue(Props[QueueReportingActor], "default-bounded-mailbox-with-zero-pushtimeout", BoundedMailboxTypes)
q.asInstanceOf[BoundedMessageQueueSemantics].pushTimeOut should ===(Duration.Zero)
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorPathSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorPathSpec.scala
index 39d1a87..4b1dd2b 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorPathSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorPathSpec.scala
@@ -12,7 +12,7 @@ class ActorPathSpec extends WordSpec with Matchers {
"An ActorPath" must {
"support parsing its String rep" in {
- val path = RootActorPath(Address("akka.tcp", "mysys")) / "user"
+ val path: akka.actor.ActorPath = RootActorPath(Address("akka.tcp", "mysys")) / "user"
ActorPath.fromString(path.toString) should ===(path)
}
@@ -30,7 +30,7 @@ class ActorPathSpec extends WordSpec with Matchers {
}
"create correct toString" in {
- val a = Address("akka.tcp", "mysys")
+ val a: akka.actor.Address = Address("akka.tcp", "mysys")
RootActorPath(a).toString should ===("akka.tcp://mysys/")
(RootActorPath(a) / "user").toString should ===("akka.tcp://mysys/user")
(RootActorPath(a) / "user" / "foo").toString should ===("akka.tcp://mysys/user/foo")
@@ -42,7 +42,7 @@ class ActorPathSpec extends WordSpec with Matchers {
}
"create correct toStringWithoutAddress" in {
- val a = Address("akka.tcp", "mysys")
+ val a: akka.actor.Address = Address("akka.tcp", "mysys")
RootActorPath(a).toStringWithoutAddress should ===("/")
(RootActorPath(a) / "user").toStringWithoutAddress should ===("/user")
(RootActorPath(a) / "user" / "foo").toStringWithoutAddress should ===("/user/foo")
@@ -54,11 +54,11 @@ class ActorPathSpec extends WordSpec with Matchers {
}
"create correct toStringWithAddress" in {
- val local = Address("akka.tcp", "mysys")
- val a = local.copy(host = Some("aaa"), port = Some(2552))
- val b = a.copy(host = Some("bb"))
- val c = a.copy(host = Some("cccc"))
- val root = RootActorPath(local)
+ val local: akka.actor.Address = Address("akka.tcp", "mysys")
+ val a: akka.actor.Address = local.copy(host = Some("aaa"), port = Some(2552))
+ val b: akka.actor.Address = a.copy(host = Some("bb"))
+ val c: akka.actor.Address = a.copy(host = Some("cccc"))
+ val root: akka.actor.RootActorPath = RootActorPath(local)
root.toStringWithAddress(a) should ===("akka.tcp://mysys@aaa:2552/")
(root / "user").toStringWithAddress(a) should ===("akka.tcp://mysys@aaa:2552/user")
(root / "user" / "foo").toStringWithAddress(a) should ===("akka.tcp://mysys@aaa:2552/user/foo")
@@ -71,7 +71,7 @@ class ActorPathSpec extends WordSpec with Matchers {
(root / "user").toStringWithAddress(c) should ===("akka.tcp://mysys@cccc:2552/user")
(root / "user" / "foo").toStringWithAddress(c) should ===("akka.tcp://mysys@cccc:2552/user/foo")
- val rootA = RootActorPath(a)
+ val rootA: akka.actor.RootActorPath = RootActorPath(a)
rootA.toStringWithAddress(b) should ===("akka.tcp://mysys@aaa:2552/")
(rootA / "user").toStringWithAddress(b) should ===("akka.tcp://mysys@aaa:2552/user")
(rootA / "user" / "foo").toStringWithAddress(b) should ===("akka.tcp://mysys@aaa:2552/user/foo")
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala
index 4dc8823..75d31af 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala
@@ -22,14 +22,14 @@ object ActorRefSpec {
class ReplyActor extends Actor {
var replyTo: ActorRef = null
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "complexRequest" ⇒ {
replyTo = sender()
- val worker = context.actorOf(Props[WorkerActor])
+ val worker: akka.actor.ActorRef = context.actorOf(Props[WorkerActor])
worker ! "work"
}
case "complexRequest2" ⇒
- val worker = context.actorOf(Props[WorkerActor])
+ val worker: akka.actor.ActorRef = context.actorOf(Props[WorkerActor])
worker ! ReplyTo(sender())
case "workDone" ⇒ replyTo ! "complexReply"
case "simpleRequest" ⇒ sender() ! "simpleReply"
@@ -38,7 +38,7 @@ object ActorRefSpec {
class WorkerActor() extends Actor {
import context.system
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "work" ⇒ {
work()
sender() ! "workDone"
@@ -55,7 +55,7 @@ object ActorRefSpec {
class SenderActor(replyActor: ActorRef, latch: TestLatch) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "complex" ⇒ replyActor ! "complexRequest"
case "complex2" ⇒ replyActor ! "complexRequest2"
case "simple" ⇒ replyActor ! "simpleRequest"
@@ -69,43 +69,43 @@ object ActorRefSpec {
}
class OuterActor(val inner: ActorRef) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "self" ⇒ sender() ! self
case x ⇒ inner forward x
}
}
class FailingOuterActor(val inner: ActorRef) extends Actor {
- val fail = new InnerActor
+ val fail: akka.actor.ActorRefSpec.InnerActor = new InnerActor
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "self" ⇒ sender() ! self
case x ⇒ inner forward x
}
}
class FailingInheritingOuterActor(_inner: ActorRef) extends OuterActor(_inner) {
- val fail = new InnerActor
+ val fail: akka.actor.ActorRefSpec.InnerActor = new InnerActor
}
class InnerActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "innerself" ⇒ sender() ! self
case other ⇒ sender() ! other
}
}
class FailingInnerActor extends Actor {
- val fail = new InnerActor
+ val fail: akka.actor.ActorRefSpec.InnerActor = new InnerActor
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "innerself" ⇒ sender() ! self
case other ⇒ sender() ! other
}
}
class FailingInheritingInnerActor extends InnerActor {
- val fail = new InnerActor
+ val fail: akka.actor.ActorRefSpec.InnerActor = new InnerActor
}
}
@@ -113,7 +113,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
import akka.actor.ActorRefSpec._
def promiseIntercept(f: ⇒ Actor)(to: Promise[Actor]): Actor = try {
- val r = f
+ val r: akka.actor.Actor = f
to.success(r)
r
} catch {
@@ -123,8 +123,8 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
}
def wrap[T](f: Promise[Actor] ⇒ T): T = {
- val result = Promise[Actor]()
- val r = f(result)
+ val result: scala.concurrent.Promise[akka.actor.Actor] = Promise[Actor]()
+ val r: T = f(result)
Await.result(result.future, 1 minute)
r
}
@@ -134,7 +134,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
"not allow Actors to be created outside of an actorOf" in {
import system.actorOf
intercept[akka.actor.ActorInitializationException] {
- new Actor { def receive = { case _ ⇒ } }
+ new Actor { def receive: PartialFunction[Any, Unit] = { case _ ⇒ } }
}
def contextStackMustBeEmpty(): Unit = ActorCell.contextStack.get.headOption should ===(None)
@@ -143,8 +143,8 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
intercept[akka.actor.ActorInitializationException] {
wrap(result ⇒
actorOf(Props(new Actor {
- val nested = promiseIntercept(new Actor { def receive = { case _ ⇒ } })(result)
- def receive = { case _ ⇒ }
+ val nested: akka.actor.Actor = promiseIntercept(new Actor { def receive: PartialFunction[Any, Unit] = { case _ ⇒ } })(result)
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
})))
}
@@ -209,7 +209,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
intercept[akka.actor.ActorInitializationException] {
wrap(result ⇒
actorOf(Props(new OuterActor(actorOf(Props(new InnerActor {
- val a = promiseIntercept(new InnerActor)(result)
+ val a: akka.actor.Actor = promiseIntercept(new InnerActor)(result)
}))))))
}
@@ -265,50 +265,50 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
}
"be serializable using Java Serialization on local node" in {
- val a = system.actorOf(Props[InnerActor])
- val esys = system.asInstanceOf[ExtendedActorSystem]
+ val a: akka.actor.ActorRef = system.actorOf(Props[InnerActor])
+ val esys: akka.actor.ExtendedActorSystem = system.asInstanceOf[ExtendedActorSystem]
import java.io._
- val baos = new ByteArrayOutputStream(8192 * 32)
- val out = new ObjectOutputStream(baos)
+ val baos: java.io.ByteArrayOutputStream = new ByteArrayOutputStream(8192 * 32)
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(baos)
out.writeObject(a)
out.flush
out.close
- val bytes = baos.toByteArray
+ val bytes: Array[Byte] = baos.toByteArray
JavaSerializer.currentSystem.withValue(esys) {
- val in = new ObjectInputStream(new ByteArrayInputStream(bytes))
- val readA = in.readObject
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes))
+ val readA: Object = in.readObject
a.isInstanceOf[ActorRefWithCell] should ===(true)
readA.isInstanceOf[ActorRefWithCell] should ===(true)
(readA eq a) should ===(true)
}
- val ser = new JavaSerializer(esys)
- val readA = ser.fromBinary(bytes, None)
+ val ser: akka.serialization.JavaSerializer = new JavaSerializer(esys)
+ val readA: AnyRef = ser.fromBinary(bytes, None)
readA.isInstanceOf[ActorRefWithCell] should ===(true)
(readA eq a) should ===(true)
}
"throw an exception on deserialize if no system in scope" in {
- val a = system.actorOf(Props[InnerActor])
+ val a: akka.actor.ActorRef = system.actorOf(Props[InnerActor])
import java.io._
- val baos = new ByteArrayOutputStream(8192 * 32)
- val out = new ObjectOutputStream(baos)
+ val baos: java.io.ByteArrayOutputStream = new ByteArrayOutputStream(8192 * 32)
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(baos)
out.writeObject(a)
out.flush
out.close
- val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
(intercept[java.lang.IllegalStateException] {
in.readObject
@@ -319,12 +319,12 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
"return EmptyLocalActorRef on deserialize if not present in actor hierarchy (and remoting is not enabled)" in {
import java.io._
- val baos = new ByteArrayOutputStream(8192 * 32)
- val out = new ObjectOutputStream(baos)
+ val baos: java.io.ByteArrayOutputStream = new ByteArrayOutputStream(8192 * 32)
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(baos)
- val sysImpl = system.asInstanceOf[ActorSystemImpl]
- val ref = system.actorOf(Props[ReplyActor], "non-existing")
- val serialized = SerializedActorRef(ref)
+ val sysImpl: akka.actor.ActorSystemImpl = system.asInstanceOf[ActorSystemImpl]
+ val ref: akka.actor.ActorRef = system.actorOf(Props[ReplyActor], "non-existing")
+ val serialized: akka.actor.SerializedActorRef = SerializedActorRef(ref)
out.writeObject(serialized)
@@ -337,26 +337,26 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
expectTerminated(ref)
JavaSerializer.currentSystem.withValue(sysImpl) {
- val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
in.readObject should ===(new EmptyLocalActorRef(sysImpl.provider, ref.path, system.eventStream))
}
}
"support nested actorOfs" in {
- val a = system.actorOf(Props(new Actor {
- val nested = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } }))
- def receive = { case _ ⇒ sender() ! nested }
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ val nested: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case _ ⇒ } }))
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ sender() ! nested }
}))
- val nested = Await.result((a ? "any").mapTo[ActorRef], timeout.duration)
+ val nested: akka.actor.ActorRef = Await.result((a ? "any").mapTo[ActorRef], timeout.duration)
a should not be null
nested should not be null
(a ne nested) should ===(true)
}
"support advanced nested actorOfs" in {
- val a = system.actorOf(Props(new OuterActor(system.actorOf(Props(new InnerActor)))))
- val inner = Await.result(a ? "innerself", timeout.duration)
+ val a: akka.actor.ActorRef = system.actorOf(Props(new OuterActor(system.actorOf(Props(new InnerActor)))))
+ val inner: Any = Await.result(a ? "innerself", timeout.duration)
Await.result(a ? a, timeout.duration) should ===(a)
Await.result(a ? "self", timeout.duration) should ===(a)
@@ -366,9 +366,9 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
}
"support reply via sender" in {
- val latch = new TestLatch(4)
- val serverRef = system.actorOf(Props[ReplyActor])
- val clientRef = system.actorOf(Props(new SenderActor(serverRef, latch)))
+ val latch: akka.testkit.TestLatch = new TestLatch(4)
+ val serverRef: akka.actor.ActorRef = system.actorOf(Props[ReplyActor])
+ val clientRef: akka.actor.ActorRef = system.actorOf(Props(new SenderActor(serverRef, latch)))
clientRef ! "complex"
clientRef ! "simple"
@@ -391,23 +391,23 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
}
"support actorOfs where the class of the actor isn't public" in {
- val a = system.actorOf(NonPublicClass.createProps())
+ val a: akka.actor.ActorRef = system.actorOf(NonPublicClass.createProps())
a.tell("pigdog", testActor)
expectMsg("pigdog")
system stop a
}
"stop when sent a poison pill" in {
- val timeout = Timeout(20.seconds)
- val ref = system.actorOf(Props(new Actor {
- def receive = {
+ val timeout: akka.util.Timeout = Timeout(20.seconds)
+ val ref: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case 5 ⇒ sender() ! "five"
case 0 ⇒ sender() ! "null"
}
}))
- val ffive = (ref.ask(5)(timeout)).mapTo[String]
- val fnull = (ref.ask(0)(timeout)).mapTo[String]
+ val ffive: scala.concurrent.Future[String] = (ref.ask(5)(timeout)).mapTo[String]
+ val fnull: scala.concurrent.Future[String] = (ref.ask(0)(timeout)).mapTo[String]
ref ! PoisonPill
Await.result(ffive, timeout.duration) should ===("five")
@@ -419,21 +419,21 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
"restart when Kill:ed" in {
filterException[ActorKilledException] {
- val latch = TestLatch(2)
+ val latch: akka.testkit.TestLatch = TestLatch(2)
- val boss = system.actorOf(Props(new Actor {
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Actor {
- override val supervisorStrategy =
+ override val supervisorStrategy: akka.actor.OneForOneStrategy =
OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1 second)(List(classOf[Throwable]))
- val ref = context.actorOf(
+ val ref: akka.actor.ActorRef = context.actorOf(
Props(new Actor {
- def receive = { case _ ⇒ }
- override def preRestart(reason: Throwable, msg: Option[Any]) = latch.countDown()
- override def postRestart(reason: Throwable) = latch.countDown()
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
+ override def preRestart(reason: Throwable, msg: Option[Any]): Unit = latch.countDown()
+ override def postRestart(reason: Throwable): Unit = latch.countDown()
}))
- def receive = { case "sendKill" ⇒ ref ! Kill }
+ def receive: PartialFunction[Any, Unit] = { case "sendKill" ⇒ ref ! Kill }
}))
boss ! "sendKill"
@@ -442,14 +442,14 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
}
"be able to check for existence of children" in {
- val parent = system.actorOf(Props(new Actor {
+ val parent: akka.actor.ActorRef = system.actorOf(Props(new Actor {
- val child = context.actorOf(
+ val child: akka.actor.ActorRef = context.actorOf(
Props(new Actor {
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}), "child")
- def receive = { case name: String ⇒ sender() ! context.child(name).isDefined }
+ def receive: PartialFunction[Any, Unit] = { case name: String ⇒ sender() ! context.child(name).isDefined }
}), "parent")
assert(Await.result((parent ? "child"), timeout.duration) === true)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala
index 3811c2d..3d96ab7 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala
@@ -20,10 +20,10 @@ object ActorSelectionSpec {
final case class GetSender(to: ActorRef) extends Query
final case class Forward(path: String, msg: Any) extends Query
- val p = Props[Node]
+ val p: akka.actor.Props = Props[Node]
class Node extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Create(name) ⇒ sender() ! context.actorOf(p, name)
case SelectString(path) ⇒ sender() ! context.actorSelection(path)
case SelectPath(path) ⇒ sender() ! context.actorSelection(path)
@@ -38,34 +38,34 @@ object ActorSelectionSpec {
class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
import ActorSelectionSpec._
- val c1 = system.actorOf(p, "c1")
- val c2 = system.actorOf(p, "c2")
- val c21 = Await.result((c2 ? Create("c21")).mapTo[ActorRef], timeout.duration)
+ val c1: akka.actor.ActorRef = system.actorOf(p, "c1")
+ val c2: akka.actor.ActorRef = system.actorOf(p, "c2")
+ val c21: akka.actor.ActorRef = Await.result((c2 ? Create("c21")).mapTo[ActorRef], timeout.duration)
- val sysImpl = system.asInstanceOf[ActorSystemImpl]
+ val sysImpl: akka.actor.ActorSystemImpl = system.asInstanceOf[ActorSystemImpl]
- val user = sysImpl.guardian
- val syst = sysImpl.systemGuardian
- val root = sysImpl.lookupRoot
+ val user: akka.actor.LocalActorRef = sysImpl.guardian
+ val syst: akka.actor.LocalActorRef = sysImpl.systemGuardian
+ val root: akka.actor.InternalActorRef = sysImpl.lookupRoot
- def empty(path: String) =
+ def empty(path: String): akka.actor.EmptyLocalActorRef =
new EmptyLocalActorRef(sysImpl.provider, path match {
case RelativeActorPath(elems) ⇒ sysImpl.lookupRoot.path / elems
}, system.eventStream)
- val idProbe = TestProbe()
+ val idProbe: akka.testkit.TestProbe = TestProbe()
def identify(selection: ActorSelection): Option[ActorRef] = {
selection.tell(Identify(selection), idProbe.ref)
- val result = idProbe.expectMsgPF() {
+ val result: Option[akka.actor.ActorRef] = idProbe.expectMsgPF() {
case ActorIdentity(`selection`, ref) ⇒ ref
}
- val asked = Await.result((selection ? Identify(selection)).mapTo[ActorIdentity], timeout.duration)
+ val asked: akka.actor.ActorIdentity = Await.result((selection ? Identify(selection)).mapTo[ActorIdentity], timeout.duration)
asked.ref should ===(result)
asked.correlationId should ===(selection)
- implicit val ec = system.dispatcher
- val resolved = Await.result(
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
+ val resolved: akka.actor.ActorRef = Await.result(
selection.resolveOne(timeout.duration).mapTo[ActorRef] recover { case _ ⇒ null },
timeout.duration)
Option(resolved) should ===(result)
@@ -111,7 +111,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
"take actor incarnation into account when comparing actor references" in {
val name = "abcdefg"
- val a1 = system.actorOf(p, name)
+ val a1: akka.actor.ActorRef = system.actorOf(p, name)
watch(a1)
a1 ! PoisonPill
expectMsgType[Terminated].actor should ===(a1)
@@ -124,7 +124,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
system.asInstanceOf[ExtendedActorSystem].provider.resolveActorRef(a1.path) != a1
}
- val a2 = system.actorOf(p, name)
+ val a2: akka.actor.ActorRef = system.actorOf(p, name)
a2.path should ===(a1.path)
a2.path.toString should ===(a1.path.toString)
a2 should not be (a1)
@@ -180,7 +180,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
"An ActorContext" must {
- val all = Seq(c1, c2, c21)
+ val all: Seq[akka.actor.ActorRef] = Seq(c1, c2, c21)
"select actors by their path" in {
def check(looker: ActorRef, pathOf: ActorRef, result: ActorRef) {
@@ -247,11 +247,11 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
import scala.collection.JavaConverters._
def checkOne(looker: ActorRef, query: Query, result: Option[ActorRef]) {
- val lookup = askNode(looker, query)
+ val lookup: Option[akka.actor.ActorRef] = askNode(looker, query)
lookup should ===(result)
}
def check(looker: ActorRef) {
- val lookname = looker.path.elements.mkString("", "/", "/")
+ val lookname: String = looker.path.elements.mkString("", "/", "/")
for (
(l, r) ← Seq(
SelectString("a/b/c") → None,
@@ -287,9 +287,9 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
}
"send messages with correct sender" in {
- implicit val sender = c1
+ implicit val sender: akka.actor.ActorRef = c1
ActorSelection(c21, "../../*") ! GetSender(testActor)
- val actors = Set() ++ receiveWhile(messages = 2) {
+ val actors: scala.collection.immutable.Set[akka.actor.ActorRef] = Set() ++ receiveWhile(messages = 2) {
case `c1` ⇒ lastSender
}
actors should ===(Set(c1, c2))
@@ -297,9 +297,9 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
}
"drop messages which cannot be delivered" in {
- implicit val sender = c2
+ implicit val sender: akka.actor.ActorRef = c2
ActorSelection(c21, "../../*/c21") ! GetSender(testActor)
- val actors = receiveWhile(messages = 2) {
+ val actors: scala.collection.immutable.Seq[akka.actor.ActorRef] = receiveWhile(messages = 2) {
case `c2` ⇒ lastSender
}
actors should ===(Seq(c21))
@@ -307,13 +307,13 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
}
"resolve one actor with explicit timeout" in {
- val s = system.actorSelection(system / "c2")
+ val s: akka.actor.ActorSelection = system.actorSelection(system / "c2")
// Java and Scala API
Await.result(s.resolveOne(1.second.dilated), timeout.duration) should ===(c2)
}
"resolve one actor with implicit timeout" in {
- val s = system.actorSelection(system / "c2")
+ val s: akka.actor.ActorSelection = system.actorSelection(system / "c2")
// Scala API; implicit timeout from DefaultTimeout trait
Await.result(s.resolveOne(), timeout.duration) should ===(c2)
}
@@ -347,25 +347,25 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
}
"send ActorSelection targeted to missing actor to deadLetters" in {
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(p.ref, classOf[DeadLetter])
system.actorSelection("/user/missing").tell("boom", testActor)
- val d = p.expectMsgType[DeadLetter]
+ val d: akka.actor.DeadLetter = p.expectMsgType[DeadLetter]
d.message should ===("boom")
d.sender should ===(testActor)
d.recipient.path.toStringWithoutAddress should ===("/user/missing")
}
"identify actors with wildcard selection correctly" in {
- val creator = TestProbe()
- implicit def self = creator.ref
- val top = system.actorOf(p, "a")
- val b1 = Await.result((top ? Create("b1")).mapTo[ActorRef], timeout.duration)
- val b2 = Await.result((top ? Create("b2")).mapTo[ActorRef], timeout.duration)
- val c = Await.result((b2 ? Create("c")).mapTo[ActorRef], timeout.duration)
- val d = Await.result((c ? Create("d")).mapTo[ActorRef], timeout.duration)
-
- val probe = TestProbe()
+ val creator: akka.testkit.TestProbe = TestProbe()
+ implicit def self: akka.actor.ActorRef = creator.ref
+ val top: akka.actor.ActorRef = system.actorOf(p, "a")
+ val b1: akka.actor.ActorRef = Await.result((top ? Create("b1")).mapTo[ActorRef], timeout.duration)
+ val b2: akka.actor.ActorRef = Await.result((top ? Create("b2")).mapTo[ActorRef], timeout.duration)
+ val c: akka.actor.ActorRef = Await.result((b2 ? Create("c")).mapTo[ActorRef], timeout.duration)
+ val d: akka.actor.ActorRef = Await.result((c ? Create("d")).mapTo[ActorRef], timeout.duration)
+
+ val probe: akka.testkit.TestProbe = TestProbe()
system.actorSelection("/user/a/*").tell(Identify(1), probe.ref)
probe.receiveN(2).map { case ActorIdentity(1, r) ⇒ r }.toSet should ===(Set[Option[ActorRef]](Some(b1), Some(b2)))
probe.expectNoMsg(200.millis)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala
index 12334d6..d3cf9b4 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala
@@ -23,13 +23,13 @@ object ActorSystemSpec {
class Waves extends Actor {
var master: ActorRef = _
- var terminaters = Set[ActorRef]()
+ var terminaters: scala.collection.immutable.Set[akka.actor.ActorRef] = Set[ActorRef]()
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case n: Int ⇒
master = sender()
terminaters = Set() ++ (for (i ← 1 to n) yield {
- val man = context.watch(context.system.actorOf(Props[Terminater]))
+ val man: akka.actor.ActorRef = context.watch(context.system.actorOf(Props[Terminater]))
man ! "run"
man
})
@@ -50,24 +50,24 @@ object ActorSystemSpec {
}
class Terminater extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "run" ⇒ context.stop(self)
}
}
class Strategy extends SupervisorStrategyConfigurator {
- def create() = OneForOneStrategy() {
+ def create(): akka.actor.OneForOneStrategy = OneForOneStrategy() {
case _ ⇒ SupervisorStrategy.Escalate
}
}
final case class FastActor(latch: TestLatch, testActor: ActorRef) extends Actor {
- val ref1 = context.actorOf(Props.empty)
- val ref2 = context.actorFor(ref1.path.toString)
+ val ref1: akka.actor.ActorRef = context.actorOf(Props.empty)
+ val ref2: akka.actor.ActorRef = context.actorFor(ref1.path.toString)
testActor ! ref2.getClass
latch.countDown()
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case _ ⇒
}
}
@@ -80,9 +80,9 @@ object ActorSystemSpec {
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) {
- val doneIt = new Switch
+ val doneIt: akka.util.Switch = new Switch
override protected[akka] def registerForExecution(mbox: Mailbox, hasMessageHint: Boolean, hasSystemMessageHint: Boolean): Boolean = {
- val ret = super.registerForExecution(mbox, hasMessageHint, hasSystemMessageHint)
+ val ret: Boolean = super.registerForExecution(mbox, hasMessageHint, hasSystemMessageHint)
doneIt.switchOn {
TestKit.awaitCond(mbox.actor.actor != null, 1.second)
mbox.actor.actor match {
@@ -112,7 +112,7 @@ object ActorSystemSpec {
}
}
- val config = s"""
+ val config: String = s"""
slow {
type="${classOf[SlowDispatcher].getName}"
}"""
@@ -150,10 +150,10 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"log dead letters" in {
- val sys = ActorSystem("LogDeadLetters", ConfigFactory.parseString("akka.loglevel=INFO").withFallback(AkkaSpec.testConf))
+ val sys: akka.actor.ActorSystem = ActorSystem("LogDeadLetters", ConfigFactory.parseString("akka.loglevel=INFO").withFallback(AkkaSpec.testConf))
try {
- val probe = TestProbe()(sys)
- val a = sys.actorOf(Props[ActorSystemSpec.Terminater])
+ val probe: akka.testkit.TestProbe = TestProbe()(sys)
+ val a: akka.actor.ActorRef = sys.actorOf(Props[ActorSystemSpec.Terminater])
probe.watch(a)
a.tell("run", probe.ref)
probe.expectTerminated(a)
@@ -167,10 +167,10 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"log dead letters sent without sender reference" in {
- val sys = ActorSystem("LogDeadLetters", ConfigFactory.parseString("akka.loglevel=INFO").withFallback(AkkaSpec.testConf))
+ val sys: akka.actor.ActorSystem = ActorSystem("LogDeadLetters", ConfigFactory.parseString("akka.loglevel=INFO").withFallback(AkkaSpec.testConf))
try {
- val probe = TestProbe()(sys)
- val a = sys.actorOf(Props[ActorSystemSpec.Terminater])
+ val probe: akka.testkit.TestProbe = TestProbe()(sys)
+ val a: akka.actor.ActorRef = sys.actorOf(Props[ActorSystemSpec.Terminater])
probe.watch(a)
a.tell("run", probe.ref)
probe.expectTerminated(a)
@@ -184,10 +184,10 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"run termination callbacks in order" in {
- val system2 = ActorSystem("TerminationCallbacks", AkkaSpec.testConf)
- val result = new ConcurrentLinkedQueue[Int]
+ val system2: akka.actor.ActorSystem = ActorSystem("TerminationCallbacks", AkkaSpec.testConf)
+ val result: java.util.concurrent.ConcurrentLinkedQueue[Int] = new ConcurrentLinkedQueue[Int]
val count = 10
- val latch = TestLatch(count)
+ val latch: akka.testkit.TestLatch = TestLatch(count)
for (i ← 1 to count) {
system2.registerOnTermination {
@@ -200,13 +200,13 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
system2.terminate()
Await.ready(latch, 5 seconds)
- val expected = (for (i ← 1 to count) yield i).reverse
+ val expected: scala.collection.immutable.IndexedSeq[Int] = (for (i ← 1 to count) yield i).reverse
immutableSeq(result) should ===(expected)
}
"awaitTermination after termination callbacks" in {
- val system2 = ActorSystem("AwaitTermination", AkkaSpec.testConf)
+ val system2: akka.actor.ActorSystem = ActorSystem("AwaitTermination", AkkaSpec.testConf)
@volatile
var callbackWasRun = false
@@ -222,11 +222,11 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"return isTerminated status correctly" in {
- val system = ActorSystem().asInstanceOf[ActorSystemImpl]
- val wt = system.whenTerminated
+ val system: akka.actor.ActorSystemImpl = ActorSystem().asInstanceOf[ActorSystemImpl]
+ val wt: scala.concurrent.Future[akka.actor.Terminated] = system.whenTerminated
wt.isCompleted should ===(false)
- val f = system.terminate()
- val terminated = Await.result(wt, 10 seconds)
+ val f: scala.concurrent.Future[akka.actor.Terminated] = system.terminate()
+ val terminated: akka.actor.Terminated = Await.result(wt, 10 seconds)
system.whenTerminated.isCompleted should ===(true)
terminated.actor should ===(system.provider.rootGuardian)
terminated.addressTerminated should ===(true)
@@ -235,7 +235,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"throw RejectedExecutionException when shutdown" in {
- val system2 = ActorSystem("AwaitTermination", AkkaSpec.testConf)
+ val system2: akka.actor.ActorSystem = ActorSystem("AwaitTermination", AkkaSpec.testConf)
Await.ready(system2.terminate(), 10 seconds)
intercept[RejectedExecutionException] {
@@ -245,8 +245,8 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
"reliably create waves of actors" in {
import system.dispatcher
- implicit val timeout = Timeout((20 seconds).dilated)
- val waves = for (i ← 1 to 3) yield system.actorOf(Props[ActorSystemSpec.Waves]) ? 50000
+ implicit val timeout: akka.util.Timeout = Timeout((20 seconds).dilated)
+ val waves: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[Any]] = for (i ← 1 to 3) yield system.actorOf(Props[ActorSystemSpec.Waves]) ? 50000
Await.result(Future.sequence(waves), timeout.duration + 5.seconds) should ===(Vector("done", "done", "done"))
}
@@ -256,14 +256,14 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"reliable deny creation of actors while shutting down" in {
- val system = ActorSystem()
+ val system: akka.actor.ActorSystem = ActorSystem()
import system.dispatcher
system.scheduler.scheduleOnce(100 millis) { system.terminate() }
var failing = false
var created = Vector.empty[ActorRef]
while (!system.whenTerminated.isCompleted) {
try {
- val t = system.actorOf(Props[ActorSystemSpec.Terminater])
+ val t: akka.actor.ActorRef = system.actorOf(Props[ActorSystemSpec.Terminater])
failing should not be true // because once failing => always failing (it’s due to shutdown)
created :+= t
if (created.size % 1000 == 0) Thread.sleep(50) // in case of unfair thread scheduling
@@ -282,7 +282,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"shut down when /user fails" in {
- implicit val system = ActorSystem("Stop", AkkaSpec.testConf)
+ implicit val system: akka.actor.ActorSystem = ActorSystem("Stop", AkkaSpec.testConf)
EventFilter[ActorKilledException]() intercept {
system.actorSelection("/user") ! Kill
Await.ready(system.whenTerminated, Duration.Inf)
@@ -290,33 +290,33 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"allow configuration of guardian supervisor strategy" in {
- implicit val system = ActorSystem(
+ implicit val system: akka.actor.ActorSystem = ActorSystem(
"Stop",
ConfigFactory.parseString("akka.actor.guardian-supervisor-strategy=akka.actor.StoppingSupervisorStrategy")
.withFallback(AkkaSpec.testConf))
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "die" ⇒ throw new Exception("hello")
}
}))
- val probe = TestProbe()
+ val probe: akka.testkit.TestProbe = TestProbe()
probe.watch(a)
EventFilter[Exception]("hello", occurrences = 1) intercept {
a ! "die"
}
- val t = probe.expectMsg(Terminated(a)(existenceConfirmed = true, addressTerminated = false))
+ val t: akka.actor.Terminated = probe.expectMsg(Terminated(a)(existenceConfirmed = true, addressTerminated = false))
t.existenceConfirmed should ===(true)
t.addressTerminated should ===(false)
shutdown(system)
}
"shut down when /user escalates" in {
- implicit val system = ActorSystem(
+ implicit val system: akka.actor.ActorSystem = ActorSystem(
"Stop",
ConfigFactory.parseString("akka.actor.guardian-supervisor-strategy=\"akka.actor.ActorSystemSpec$Strategy\"")
.withFallback(AkkaSpec.testConf))
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "die" ⇒ throw new Exception("hello")
}
}))
@@ -327,19 +327,19 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"work with a passed in ExecutionContext" in {
- val ecProbe = TestProbe()
- val ec = new ActorSystemSpec.TestExecutionContext(ecProbe.ref, ExecutionContexts.global())
+ val ecProbe: akka.testkit.TestProbe = TestProbe()
+ val ec: akka.actor.ActorSystemSpec.TestExecutionContext = new ActorSystemSpec.TestExecutionContext(ecProbe.ref, ExecutionContexts.global())
- val system2 = ActorSystem(name = "default", defaultExecutionContext = Some(ec))
+ val system2: akka.actor.ActorSystem = ActorSystem(name = "default", defaultExecutionContext = Some(ec))
try {
- val ref = system2.actorOf(Props(new Actor {
- def receive = {
+ val ref: akka.actor.ActorRef = system2.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "ping" ⇒ sender() ! "pong"
}
}))
- val probe = TestProbe()
+ val probe: akka.testkit.TestProbe = TestProbe()
ref.tell("ping", probe.ref)
@@ -351,15 +351,15 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"not use passed in ExecutionContext if executor is configured" in {
- val ecProbe = TestProbe()
- val ec = new ActorSystemSpec.TestExecutionContext(ecProbe.ref, ExecutionContexts.global())
+ val ecProbe: akka.testkit.TestProbe = TestProbe()
+ val ec: akka.actor.ActorSystemSpec.TestExecutionContext = new ActorSystemSpec.TestExecutionContext(ecProbe.ref, ExecutionContexts.global())
- val config = ConfigFactory.parseString("akka.actor.default-dispatcher.executor = \"fork-join-executor\"")
- val system2 = ActorSystem(name = "default", config = Some(config), defaultExecutionContext = Some(ec))
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("akka.actor.default-dispatcher.executor = \"fork-join-executor\"")
+ val system2: akka.actor.ActorSystem = ActorSystem(name = "default", config = Some(config), defaultExecutionContext = Some(ec))
try {
- val ref = system2.actorOf(TestActors.echoActorProps)
- val probe = TestProbe()
+ val ref: akka.actor.ActorRef = system2.actorOf(TestActors.echoActorProps)
+ val probe: akka.testkit.TestProbe = TestProbe()
ref.tell("ping", probe.ref)
@@ -371,7 +371,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"not allow top-level actor creation with custom guardian" in {
- val sys = new ActorSystemImpl("custom", ConfigFactory.defaultReference(),
+ val sys: akka.actor.ActorSystemImpl = new ActorSystemImpl("custom", ConfigFactory.defaultReference(),
getClass.getClassLoader, None, Some(Props.empty), ActorSystemSetup.empty)
sys.start()
try {
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorTimeoutSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorTimeoutSpec.scala
index b33955e..10b5ac2 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorTimeoutSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorTimeoutSpec.scala
@@ -12,23 +12,23 @@ import akka.pattern.{ ask, AskTimeoutException }
class ActorTimeoutSpec extends AkkaSpec {
- val testTimeout = 200.millis.dilated
- val leeway = 500.millis.dilated
+ val testTimeout: scala.concurrent.duration.FiniteDuration = 200.millis.dilated
+ val leeway: scala.concurrent.duration.FiniteDuration = 500.millis.dilated
system.eventStream.publish(Mute(EventFilter.warning(pattern = ".*unhandled message from.*hallo")))
"An Actor-based Future" must {
"use implicitly supplied timeout" in {
- implicit val timeout = Timeout(testTimeout)
- val echo = system.actorOf(Props.empty)
- val f = (echo ? "hallo")
+ implicit val timeout: akka.util.Timeout = Timeout(testTimeout)
+ val echo: akka.actor.ActorRef = system.actorOf(Props.empty)
+ val f: scala.concurrent.Future[Any] = (echo ? "hallo")
intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) }
}
"use explicitly supplied timeout" in {
- val echo = system.actorOf(Props.empty)
- val f = echo.?("hallo")(testTimeout)
+ val echo: akka.actor.ActorRef = system.actorOf(Props.empty)
+ val f: scala.concurrent.Future[Any] = echo.?("hallo")(testTimeout)
intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) }
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala
index 80fd271..ec79e1c 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala
@@ -17,7 +17,7 @@ import org.scalatest.BeforeAndAfterEach
object ActorWithBoundedStashSpec {
class StashingActor extends Actor with Stash {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case msg: String if msg.startsWith("hello") ⇒
stash()
sender() ! "ok"
@@ -36,7 +36,7 @@ object ActorWithBoundedStashSpec {
class StashingActorWithOverflow extends Actor with Stash {
var numStashed = 0
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case msg: String if msg.startsWith("hello") ⇒
numStashed += 1
try { stash(); sender() ! "ok" } catch {
@@ -127,22 +127,22 @@ class ActorWithBoundedStashSpec extends AkkaSpec(ActorWithBoundedStashSpec.testC
"An Actor with Stash" must {
"end up in DeadLetters in case of a capacity violation when configured via dispatcher" in {
- val stasher = system.actorOf(Props[StashingActor].withDispatcher(dispatcherId1))
+ val stasher: akka.actor.ActorRef = system.actorOf(Props[StashingActor].withDispatcher(dispatcherId1))
testDeadLetters(stasher)
}
"end up in DeadLetters in case of a capacity violation when configured via mailbox" in {
- val stasher = system.actorOf(Props[StashingActor].withMailbox(mailboxId1))
+ val stasher: akka.actor.ActorRef = system.actorOf(Props[StashingActor].withMailbox(mailboxId1))
testDeadLetters(stasher)
}
"throw a StashOverflowException in case of a stash capacity violation when configured via dispatcher" in {
- val stasher = system.actorOf(Props[StashingActorWithOverflow].withDispatcher(dispatcherId2))
+ val stasher: akka.actor.ActorRef = system.actorOf(Props[StashingActorWithOverflow].withDispatcher(dispatcherId2))
testStashOverflowException(stasher)
}
"throw a StashOverflowException in case of a stash capacity violation when configured via mailbox" in {
- val stasher = system.actorOf(Props[StashingActorWithOverflow].withMailbox(mailboxId2))
+ val stasher: akka.actor.ActorRef = system.actorOf(Props[StashingActorWithOverflow].withMailbox(mailboxId2))
testStashOverflowException(stasher)
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala
index 62bd418..4e298de 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala
@@ -25,7 +25,7 @@ object ActorWithStashSpec {
case _ ⇒ // do nothing
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "hello" ⇒
state.s = "hello"
unstashAll()
@@ -35,7 +35,7 @@ object ActorWithStashSpec {
}
class StashingTwiceActor extends Actor with Stash {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "hello" ⇒
try {
stash()
@@ -50,7 +50,7 @@ object ActorWithStashSpec {
class ActorWithProtocol extends Actor with Stash {
import context.system
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "open" ⇒
unstashAll()
context.become {
@@ -66,16 +66,16 @@ object ActorWithStashSpec {
}
class WatchedActor extends Actor {
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}
class TerminatedMessageStashingActor(probe: ActorRef) extends Actor with Stash {
- val watched = context.watch(context.actorOf(Props[WatchedActor]))
+ val watched: akka.actor.ActorRef = context.watch(context.actorOf(Props[WatchedActor]))
var stashed = false
context.stop(watched)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Terminated(`watched`) ⇒
if (!stashed) {
stash()
@@ -89,7 +89,7 @@ object ActorWithStashSpec {
object state {
@volatile
var s: String = ""
- val finished = TestBarrier(2)
+ val finished: akka.testkit.TestBarrier = TestBarrier(2)
var expectedException: TestLatch = null
}
@@ -108,12 +108,12 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa
system.eventStream.publish(Mute(EventFilter[Exception]("Crashing...")))
}
- override def beforeEach() = state.finished.reset
+ override def beforeEach(): Unit = state.finished.reset
"An Actor with Stash" must {
"stash messages" in {
- val stasher = system.actorOf(Props(new StashingActor))
+ val stasher: akka.actor.ActorRef = system.actorOf(Props(new StashingActor))
stasher ! "bye"
stasher ! "hello"
state.finished.await
@@ -121,7 +121,7 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa
}
"support protocols" in {
- val protoActor = system.actorOf(Props[ActorWithProtocol])
+ val protoActor: akka.actor.ActorRef = system.actorOf(Props[ActorWithProtocol])
protoActor ! "open"
protoActor ! "write"
protoActor ! "open"
@@ -134,21 +134,21 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa
"throw an IllegalStateException if the same messages is stashed twice" in {
state.expectedException = new TestLatch
- val stasher = system.actorOf(Props[StashingTwiceActor])
+ val stasher: akka.actor.ActorRef = system.actorOf(Props[StashingTwiceActor])
stasher ! "hello"
stasher ! "hello"
Await.ready(state.expectedException, 10 seconds)
}
"process stashed messages after restart" in {
- val boss = system.actorOf(Props(new Supervisor(
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1 second)(List(classOf[Throwable])))))
- val restartLatch = new TestLatch
- val hasMsgLatch = new TestLatch
+ val restartLatch: akka.testkit.TestLatch = new TestLatch
+ val hasMsgLatch: akka.testkit.TestLatch = new TestLatch
- val slaveProps = Props(new Actor with Stash {
- def receive = {
+ val slaveProps: akka.actor.Props = Props(new Actor with Stash {
+ def receive: PartialFunction[Any, Unit] = {
case "crash" ⇒
throw new Exception("Crashing...")
@@ -161,13 +161,13 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa
hasMsgLatch.open()
}
- override def preRestart(reason: Throwable, message: Option[Any]) = {
+ override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
if (!restartLatch.isOpen)
restartLatch.open()
super.preRestart(reason, message)
}
})
- val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
+ val slave: akka.actor.ActorRef = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
slave ! "hello"
slave ! "crash"
@@ -187,7 +187,7 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa
"allow using whenRestarted" in {
import ActorDSL._
- val a = actor(new ActWithStash {
+ val a: akka.actor.ActorRef = actor(new ActWithStash {
become {
case "die" ⇒ throw new RuntimeException("dying")
}
@@ -203,7 +203,7 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa
"allow using whenStopping" in {
import ActorDSL._
- val a = actor(new ActWithStash {
+ val a: akka.actor.ActorRef = actor(new ActWithStash {
whenStopping {
testActor ! "stopping"
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/Bench.scala b/akka-actor-tests/src/test/scala/akka/actor/Bench.scala
index 1351a3f..412a245 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/Bench.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/Bench.scala
@@ -19,7 +19,7 @@ object Chameneos {
case object BLUE extends Colour
case object FADED extends Colour
- val colours = Array[Colour](BLUE, RED, YELLOW)
+ val colours: Array[akka.actor.Chameneos.Colour] = Array[Colour](BLUE, RED, YELLOW)
var start = 0L
var end = 0L
@@ -28,7 +28,7 @@ object Chameneos {
var meetings = 0
mall ! Meet(self, colour)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Meet(from, otherColour) ⇒
colour = complement(otherColour)
meetings = meetings + 1
@@ -67,7 +67,7 @@ object Chameneos {
case FADED ⇒ FADED
}
- override def toString = cid + "(" + colour + ")"
+ override def toString: String = cid + "(" + colour + ")"
}
class Mall(var n: Int, numChameneos: Int) extends Actor {
@@ -75,11 +75,11 @@ object Chameneos {
var sumMeetings = 0
var numFaded = 0
- override def preStart() = {
+ override def preStart(): Unit = {
for (i ← 0 until numChameneos) context.actorOf(Props(new Chameneo(self, colours(i % 3), i)))
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case MeetingCount(i) ⇒
numFaded += 1
sumMeetings += i
@@ -107,8 +107,8 @@ object Chameneos {
def run(): Unit = {
// System.setProperty("akka.config", "akka.conf")
Chameneos.start = System.currentTimeMillis
- val system = ActorSystem()
- val actor = system.actorOf(Props(new Mall(1000000, 4)))
+ val system: akka.actor.ActorSystem = ActorSystem()
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Mall(1000000, 4)))
Thread.sleep(10000)
println("Elapsed: " + (end - start))
system.terminate()
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala
index b063d17..fdc935d 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala
@@ -10,9 +10,9 @@ object ConsistencySpec {
val minThreads = 1
val maxThreads = 2000
val factor = 1.5d
- val threads = ThreadPoolConfig.scaledPoolSize(minThreads, factor, maxThreads) // Make sure we have more threads than cores
+ val threads: Int = ThreadPoolConfig.scaledPoolSize(minThreads, factor, maxThreads) // Make sure we have more threads than cores
- val config = s"""
+ val config: String = s"""
consistency-dispatcher {
throughput = 1
executor = "fork-join-executor"
@@ -26,10 +26,10 @@ object ConsistencySpec {
class CacheMisaligned(var value: Long, var padding1: Long, var padding2: Long, var padding3: Int) //Vars, no final fences
class ConsistencyCheckingActor extends Actor {
- var left = new CacheMisaligned(42, 0, 0, 0) //var
- var right = new CacheMisaligned(0, 0, 0, 0) //var
+ var left: akka.actor.ConsistencySpec.CacheMisaligned = new CacheMisaligned(42, 0, 0, 0) //var
+ var right: akka.actor.ConsistencySpec.CacheMisaligned = new CacheMisaligned(0, 0, 0, 0) //var
var lastStep = -1L
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case step: Long ⇒
if (lastStep != (step - 1))
@@ -56,9 +56,9 @@ class ConsistencySpec extends AkkaSpec(ConsistencySpec.config) {
"The Akka actor model implementation" must {
"provide memory consistency" in {
- val noOfActors = threads + 1
- val props = Props[ConsistencyCheckingActor].withDispatcher("consistency-dispatcher")
- val actors = Vector.fill(noOfActors)(system.actorOf(props))
+ val noOfActors: Int = threads + 1
+ val props: akka.actor.Props = Props[ConsistencyCheckingActor].withDispatcher("consistency-dispatcher")
+ val actors: scala.collection.immutable.Vector[akka.actor.ActorRef] = Vector.fill(noOfActors)(system.actorOf(props))
for (i ← 0L until 10000L) {
actors.foreach(_.tell(i, testActor))
diff --git a/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala
index 62aa77b..c712186 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala
@@ -16,14 +16,14 @@ import java.util.concurrent.TimeoutException
class CoordinatedShutdownSpec extends AkkaSpec {
- def extSys = system.asInstanceOf[ExtendedActorSystem]
+ def extSys: akka.actor.ExtendedActorSystem = system.asInstanceOf[ExtendedActorSystem]
// some convenience to make the test readable
def phase(dependsOn: String*): Phase = Phase(dependsOn.toSet, timeout = 10.seconds, recover = true)
val emptyPhase: Phase = Phase(Set.empty, timeout = 10.seconds, recover = true)
private def checkTopologicalSort(phases: Map[String, Phase]): List[String] = {
- val result = CoordinatedShutdown.topologicalSort(phases)
+ val result: List[String] = CoordinatedShutdown.topologicalSort(phases)
result.zipWithIndex.foreach {
case (phase, i) ⇒
phases.get(phase) match {
@@ -50,7 +50,7 @@ class CoordinatedShutdownSpec extends AkkaSpec {
checkTopologicalSort(Map(
"b" → phase("a"))) should ===(List("a", "b"))
- val result1 = checkTopologicalSort(Map(
+ val result1: List[String] = checkTopologicalSort(Map(
"c" → phase("a"), "b" → phase("a")))
result1.head should ===("a")
// b, c can be in any order
@@ -62,7 +62,7 @@ class CoordinatedShutdownSpec extends AkkaSpec {
checkTopologicalSort(Map(
"b" → phase("a"), "c" → phase("a", "b"))) should ===(List("a", "b", "c"))
- val result2 = checkTopologicalSort(Map(
+ val result2: List[String] = checkTopologicalSort(Map(
"c" → phase("a", "b")))
result2.last should ===("c")
// a, b can be in any order
@@ -73,7 +73,7 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"e" → phase("d"))) should ===(
List("a", "b", "c", "d", "e"))
- val result3 = checkTopologicalSort(Map(
+ val result3: List[String] = checkTopologicalSort(Map(
"a2" → phase("a1"), "a3" → phase("a2"),
"b2" → phase("b1"), "b3" → phase("b2")))
val (a, b) = result3.partition(_.charAt(0) == 'a')
@@ -123,11 +123,11 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"run ordered phases" in {
import system.dispatcher
- val phases = Map(
+ val phases: scala.collection.immutable.Map[String, akka.actor.CoordinatedShutdown.Phase] = Map(
"a" → emptyPhase,
"b" → phase("a"),
"c" → phase("b", "a"))
- val co = new CoordinatedShutdown(extSys, phases)
+ val co: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(extSys, phases)
co.addTask("a", "a1") { () ⇒
testActor ! "A"
Future.successful(Done)
@@ -154,11 +154,11 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"run from a given phase" in {
import system.dispatcher
- val phases = Map(
+ val phases: scala.collection.immutable.Map[String, akka.actor.CoordinatedShutdown.Phase] = Map(
"a" → emptyPhase,
"b" → phase("a"),
"c" → phase("b", "a"))
- val co = new CoordinatedShutdown(extSys, phases)
+ val co: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(extSys, phases)
co.addTask("a", "a1") { () ⇒
testActor ! "A"
Future.successful(Done)
@@ -177,8 +177,8 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"only run once" in {
import system.dispatcher
- val phases = Map("a" → emptyPhase)
- val co = new CoordinatedShutdown(extSys, phases)
+ val phases: scala.collection.immutable.Map[String, akka.actor.CoordinatedShutdown.Phase] = Map("a" → emptyPhase)
+ val co: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(extSys, phases)
co.addTask("a", "a1") { () ⇒
testActor ! "A"
Future.successful(Done)
@@ -192,11 +192,11 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"continue after timeout or failure" in {
import system.dispatcher
- val phases = Map(
+ val phases: scala.collection.immutable.Map[String, akka.actor.CoordinatedShutdown.Phase] = Map(
"a" → emptyPhase,
"b" → Phase(dependsOn = Set("a"), timeout = 100.millis, recover = true),
"c" → phase("b", "a"))
- val co = new CoordinatedShutdown(extSys, phases)
+ val co: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(extSys, phases)
co.addTask("a", "a1") { () ⇒
testActor ! "A"
Future.failed(new RuntimeException("boom"))
@@ -226,10 +226,10 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"abort if recover=off" in {
import system.dispatcher
- val phases = Map(
+ val phases: scala.collection.immutable.Map[String, akka.actor.CoordinatedShutdown.Phase] = Map(
"b" → Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false),
"c" → phase("b", "a"))
- val co = new CoordinatedShutdown(extSys, phases)
+ val co: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(extSys, phases)
co.addTask("b", "b1") { () ⇒
testActor ! "B"
Promise[Done]().future // never completed
@@ -238,7 +238,7 @@ class CoordinatedShutdownSpec extends AkkaSpec {
testActor ! "C"
Future.successful(Done)
}
- val result = co.run()
+ val result: scala.concurrent.Future[akka.Done] = co.run()
expectMsg("B")
intercept[TimeoutException] {
Await.result(result, remainingOrDefault)
@@ -248,10 +248,10 @@ class CoordinatedShutdownSpec extends AkkaSpec {
"be possible to add tasks in later phase from task in earlier phase" in {
import system.dispatcher
- val phases = Map(
+ val phases: scala.collection.immutable.Map[String, akka.actor.CoordinatedShutdown.Phase] = Map(
"a" → emptyPhase,
"b" → phase("a"))
- val co = new CoordinatedShutdown(extSys, phases)
+ val co: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(extSys, phases)
co.addTask("a", "a1") { () ⇒
testActor ! "A"
co.addTask("b", "b1") { () ⇒
diff --git a/akka-actor-tests/src/test/scala/akka/actor/DeadLetterSupressionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/DeadLetterSupressionSpec.scala
index 209d42d..5591ef8 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/DeadLetterSupressionSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/DeadLetterSupressionSpec.scala
@@ -22,19 +22,19 @@ object DeadLetterSupressionSpec {
class DeadLetterSupressionSpec extends AkkaSpec with ImplicitSender {
import DeadLetterSupressionSpec._
- val deadActor = system.actorOf(TestActors.echoActorProps)
+ val deadActor: akka.actor.ActorRef = system.actorOf(TestActors.echoActorProps)
watch(deadActor)
deadActor ! PoisonPill
expectTerminated(deadActor)
s"must suppress message from default dead-letters logging (sent to dead: ${Logging.simpleName(deadActor)})" in {
- val deadListener = TestProbe()
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val suppressedListener = TestProbe()
+ val suppressedListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(suppressedListener.ref, classOf[SuppressedDeadLetter])
- val allListener = TestProbe()
+ val allListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(allListener.ref, classOf[AllDeadLetters])
deadActor ! SuppressedMsg
@@ -52,13 +52,13 @@ class DeadLetterSupressionSpec extends AkkaSpec with ImplicitSender {
}
s"must suppress message from default dead-letters logging (sent to dead: ${Logging.simpleName(system.deadLetters)})" in {
- val deadListener = TestProbe()
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val suppressedListener = TestProbe()
+ val suppressedListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(suppressedListener.ref, classOf[SuppressedDeadLetter])
- val allListener = TestProbe()
+ val allListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(allListener.ref, classOf[AllDeadLetters])
system.deadLetters ! SuppressedMsg
diff --git a/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala
index 2f3137d..8c2b601 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala
@@ -19,24 +19,24 @@ class LocalDeathWatchSpec extends AkkaSpec("""
object DeathWatchSpec {
class Watcher(target: ActorRef, testActor: ActorRef) extends Actor {
context.watch(target)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case t: Terminated ⇒ testActor forward WrappedTerminated(t)
case x ⇒ testActor forward x
}
}
- def props(target: ActorRef, testActor: ActorRef) =
+ def props(target: ActorRef, testActor: ActorRef): akka.actor.Props =
Props(classOf[Watcher], target, testActor)
class EmptyWatcher(target: ActorRef) extends Actor {
context.watch(target)
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}
class NKOTBWatcher(testActor: ActorRef) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "NKOTB" ⇒
- val currentKid = context.watch(context.actorOf(Props(new Actor { def receive = { case "NKOTB" ⇒ context stop self } }), "kid"))
+ val currentKid: akka.actor.ActorRef = context.watch(context.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case "NKOTB" ⇒ context stop self } }), "kid"))
currentKid forward "NKOTB"
context become {
case Terminated(`currentKid`) ⇒
@@ -47,7 +47,7 @@ object DeathWatchSpec {
}
class WUWatcher extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case W(ref) ⇒ context watch ref
case U(ref) ⇒ context unwatch ref
case Latches(t1: TestLatch, t2: TestLatch) ⇒
@@ -73,17 +73,17 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
import DeathWatchSpec._
- lazy val supervisor = system.actorOf(Props(classOf[Supervisor], SupervisorStrategy.defaultStrategy), "watchers")
+ lazy val supervisor: akka.actor.ActorRef = system.actorOf(Props(classOf[Supervisor], SupervisorStrategy.defaultStrategy), "watchers")
- def startWatching(target: ActorRef) = Await.result((supervisor ? props(target, testActor)).mapTo[ActorRef], 3 seconds)
+ def startWatching(target: ActorRef): akka.actor.ActorRef = Await.result((supervisor ? props(target, testActor)).mapTo[ActorRef], 3 seconds)
"The Death Watch" must {
- def expectTerminationOf(actorRef: ActorRef) = expectMsgPF(5 seconds, actorRef + ": Stopped or Already terminated when linking") {
+ def expectTerminationOf(actorRef: ActorRef): Boolean = expectMsgPF(5 seconds, actorRef + ": Stopped or Already terminated when linking") {
case WrappedTerminated(Terminated(`actorRef`)) ⇒ true
}
"notify with one Terminated message when an Actor is stopped" in {
- val terminal = system.actorOf(Props.empty)
+ val terminal: akka.actor.ActorRef = system.actorOf(Props.empty)
startWatching(terminal) ! "hallo"
expectMsg("hallo")
@@ -93,7 +93,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
}
"notify with one Terminated message when an Actor is already dead" in {
- val terminal = system.actorOf(Props.empty)
+ val terminal: akka.actor.ActorRef = system.actorOf(Props.empty)
terminal ! PoisonPill
@@ -102,7 +102,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
}
"notify with all monitors with one Terminated message when an Actor is stopped" in {
- val terminal = system.actorOf(Props.empty)
+ val terminal: akka.actor.ActorRef = system.actorOf(Props.empty)
val monitor1, monitor2, monitor3 = startWatching(terminal)
terminal ! PoisonPill
@@ -117,12 +117,12 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
}
"notify with _current_ monitors with one Terminated message when an Actor is stopped" in {
- val terminal = system.actorOf(Props.empty)
+ val terminal: akka.actor.ActorRef = system.actorOf(Props.empty)
val monitor1, monitor3 = startWatching(terminal)
- val monitor2 = system.actorOf(Props(new Actor {
+ val monitor2: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.watch(terminal)
context.unwatch(terminal)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "ping" ⇒ sender() ! "pong"
case t: Terminated ⇒ testActor ! WrappedTerminated(t)
}
@@ -144,12 +144,12 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
"notify with a Terminated message once when an Actor is stopped but not when restarted" in {
filterException[ActorKilledException] {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 2)(List(classOf[Exception])))))
- val terminalProps = TestActors.echoActorProps
- val terminal = Await.result((supervisor ? terminalProps).mapTo[ActorRef], timeout.duration)
+ val terminalProps: akka.actor.Props = TestActors.echoActorProps
+ val terminal: akka.actor.ActorRef = Await.result((supervisor ? terminalProps).mapTo[ActorRef], timeout.duration)
- val monitor = startWatching(terminal)
+ val monitor: akka.actor.ActorRef = startWatching(terminal)
terminal ! Kill
terminal ! Kill
@@ -165,21 +165,21 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
"fail a monitor which does not handle Terminated()" in {
filterEvents(EventFilter[ActorKilledException](), EventFilter[DeathPactException]()) {
- val strategy = new OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider) {
- override def handleFailure(context: ActorContext, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]) = {
+ val strategy: akka.actor.OneForOneStrategy = new OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider) {
+ override def handleFailure(context: ActorContext, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Boolean = {
testActor.tell(FF(Failed(child, cause, 0)), child)
super.handleFailure(context, child, cause, stats, children)
}
}
- val supervisor = system.actorOf(Props(new Supervisor(strategy)).withDeploy(Deploy.local))
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(strategy)).withDeploy(Deploy.local))
- val failed = Await.result((supervisor ? Props.empty).mapTo[ActorRef], timeout.duration)
- val brother = Await.result((supervisor ? Props(classOf[EmptyWatcher], failed)).mapTo[ActorRef], timeout.duration)
+ val failed: akka.actor.ActorRef = Await.result((supervisor ? Props.empty).mapTo[ActorRef], timeout.duration)
+ val brother: akka.actor.ActorRef = Await.result((supervisor ? Props(classOf[EmptyWatcher], failed)).mapTo[ActorRef], timeout.duration)
startWatching(brother)
failed ! Kill
- val result = receiveWhile(3 seconds, messages = 3) {
+ val result: scala.collection.immutable.Seq[Int] = receiveWhile(3 seconds, messages = 3) {
case FF(Failed(_, _: ActorKilledException, _)) if lastSender eq failed ⇒ 1
case FF(Failed(_, DeathPactException(`failed`), _)) if lastSender eq brother ⇒ 2
case WrappedTerminated(Terminated(`brother`)) ⇒ 3
@@ -190,7 +190,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
}
"be able to watch a child with the same name after the old died" in {
- val parent = system.actorOf(Props(classOf[NKOTBWatcher], testActor).withDeploy(Deploy.local))
+ val parent: akka.actor.ActorRef = system.actorOf(Props(classOf[NKOTBWatcher], testActor).withDeploy(Deploy.local))
parent ! "NKOTB"
expectMsg("GREEN")
@@ -199,7 +199,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
}
"only notify when watching" in {
- val subject = system.actorOf(Props[EmptyActor]())
+ val subject: akka.actor.ActorRef = system.actorOf(Props[EmptyActor]())
testActor.asInstanceOf[InternalActorRef]
.sendSystemMessage(DeathWatchNotification(subject, existenceConfirmed = true, addressTerminated = false))
@@ -210,8 +210,8 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout
"discard Terminated when unwatched between sysmsg and processing" in {
val t1, t2 = TestLatch()
- val w = system.actorOf(Props[WUWatcher]().withDeploy(Deploy.local), "myDearWatcher")
- val p = TestProbe()
+ val w: akka.actor.ActorRef = system.actorOf(Props[WUWatcher]().withDeploy(Deploy.local), "myDearWatcher")
+ val p: akka.testkit.TestProbe = TestProbe()
w ! W(p.ref)
w ! Latches(t1, t2)
Await.ready(t1, 3.seconds)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala
index 7f8ea0a..8c35650 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala
@@ -13,7 +13,7 @@ import akka.routing._
import scala.concurrent.duration._
object DeployerSpec {
- val deployerConf = ConfigFactory.parseString("""
+ val deployerConf: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.actor.deployment {
/service1 {
}
@@ -70,7 +70,7 @@ object DeployerSpec {
""", ConfigParseOptions.defaults)
class RecipeActor extends Actor {
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
}
@@ -80,7 +80,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
"be able to parse 'akka.actor.deployment._' with all default values" in {
val service = "/service1"
- val deployment = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
+ val deployment: Option[akka.actor.Deploy] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
deployment should ===(Some(
Deploy(
@@ -94,13 +94,13 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
"use None deployment for undefined service" in {
val service = "/undefined"
- val deployment = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
+ val deployment: Option[akka.actor.Deploy] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
deployment should ===(None)
}
"be able to parse 'akka.actor.deployment._' with dispatcher config" in {
val service = "/service3"
- val deployment = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
+ val deployment: Option[akka.actor.Deploy] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
deployment should ===(Some(
Deploy(
@@ -114,7 +114,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
"be able to parse 'akka.actor.deployment._' with mailbox config" in {
val service = "/service4"
- val deployment = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
+ val deployment: Option[akka.actor.Deploy] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
deployment should ===(Some(
Deploy(
@@ -128,7 +128,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
"detect invalid number-of-instances" in {
intercept[com.typesafe.config.ConfigException.WrongType] {
- val invalidDeployerConf = ConfigFactory.parseString("""
+ val invalidDeployerConf: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.actor.deployment {
/service-invalid-number-of-instances {
router = round-robin-pool
@@ -142,8 +142,8 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
"detect invalid deployment path" in {
- val e = intercept[InvalidActorNameException] {
- val invalidDeployerConf = ConfigFactory.parseString("""
+ val e: akka.actor.InvalidActorNameException = intercept[InvalidActorNameException] {
+ val invalidDeployerConf: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.actor.deployment {
/gul/ubåt {
router = round-robin-pool
@@ -183,7 +183,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
"be able to parse 'akka.actor.deployment._' with router resizer" in {
- val resizer = DefaultResizer()
+ val resizer: akka.routing.DefaultResizer = DefaultResizer()
assertRouting("/service-resizer", RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)), "/service-resizer")
}
@@ -200,7 +200,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
"have correct router mappings" in {
- val mapping = system.asInstanceOf[ExtendedActorSystem].provider.deployer.routerTypeMapping
+ val mapping: Map[String, String] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.routerTypeMapping
mapping("from-code") should ===(classOf[akka.routing.NoRouter].getName)
mapping("round-robin-pool") should ===(classOf[akka.routing.RoundRobinPool].getName)
mapping("round-robin-group") should ===(classOf[akka.routing.RoundRobinGroup].getName)
@@ -217,12 +217,12 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
def assertNoRouting(service: String): Unit = {
- val deployment = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
+ val deployment: Option[akka.actor.Deploy] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
deployment shouldNot be(defined)
}
def assertRouting(service: String, expected: RouterConfig, expectPath: String): Unit = {
- val deployment = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
+ val deployment: Option[akka.actor.Deploy] = system.asInstanceOf[ExtendedActorSystem].provider.deployer.lookup(service.split("/").drop(1))
deployment.map(_.path).getOrElse("NOT FOUND") should ===(expectPath)
deployment.get.routerConfig.getClass should ===(expected.getClass)
deployment.get.scope should ===(NoScopeGiven)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ExtensionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ExtensionSpec.scala
index bb7a87e..6848e57 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ExtensionSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ExtensionSpec.scala
@@ -16,22 +16,22 @@ import scala.util.control.NoStackTrace
class JavaExtensionSpec extends JavaExtension with JUnitSuiteLike
object TestExtension extends ExtensionId[TestExtension] with ExtensionIdProvider {
- def lookup = this
- def createExtension(s: ExtendedActorSystem) = new TestExtension(s)
+ def lookup: akka.actor.TestExtension.type = this
+ def createExtension(s: ExtendedActorSystem): akka.actor.TestExtension = new TestExtension(s)
}
// Dont't place inside ActorSystemSpec object, since it will not be garbage collected and reference to system remains
class TestExtension(val system: ExtendedActorSystem) extends Extension
object FailingTestExtension extends ExtensionId[FailingTestExtension] with ExtensionIdProvider {
- def lookup = this
- def createExtension(s: ExtendedActorSystem) = new FailingTestExtension(s)
+ def lookup: akka.actor.FailingTestExtension.type = this
+ def createExtension(s: ExtendedActorSystem): akka.actor.FailingTestExtension = new FailingTestExtension(s)
class TestException extends IllegalArgumentException("ERR") with NoStackTrace
}
object InstanceCountingExtension extends ExtensionId[DummyExtensionImpl] with ExtensionIdProvider {
- val createCount = new AtomicInteger(0)
+ val createCount: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
override def createExtension(system: ExtendedActorSystem): DummyExtensionImpl = {
createCount.addAndGet(1)
new DummyExtensionImpl
@@ -44,7 +44,7 @@ class DummyExtensionImpl extends Extension
// Dont't place inside ActorSystemSpec object, since it will not be garbage collected and reference to system remains
class FailingTestExtension(val system: ExtendedActorSystem) extends Extension {
// first time the actor is created
- val ref = system.actorOf(Props.empty, "uniqueName")
+ val ref: akka.actor.ActorRef = system.actorOf(Props.empty, "uniqueName")
// but the extension initialization fails
// second time it will throw exception when trying to create actor with same name,
// but we want to see the first exception every time
@@ -56,8 +56,8 @@ class ExtensionSpec extends WordSpec with Matchers {
"The ActorSystem extensions support" should {
"support extensions" in {
- val config = ConfigFactory.parseString("""akka.extensions = ["akka.actor.TestExtension"]""")
- val system = ActorSystem("extensions", config)
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""akka.extensions = ["akka.actor.TestExtension"]""")
+ val system: akka.actor.ActorSystem = ActorSystem("extensions", config)
// TestExtension is configured and should be loaded at startup
system.hasExtension(TestExtension) should ===(true)
@@ -68,7 +68,7 @@ class ExtensionSpec extends WordSpec with Matchers {
}
"handle extensions that fail to initialize" in {
- val system = ActorSystem("extensions")
+ val system: akka.actor.ActorSystem = ActorSystem("extensions")
intercept[FailingTestExtension.TestException] {
FailingTestExtension(system)
@@ -83,7 +83,7 @@ class ExtensionSpec extends WordSpec with Matchers {
"fail the actor system if an extension listed in akka.extensions fails to start" in {
intercept[RuntimeException] {
- val system = ActorSystem("failing", ConfigFactory.parseString(
+ val system: akka.actor.ActorSystem = ActorSystem("failing", ConfigFactory.parseString(
"""
akka.extensions = ["akka.actor.FailingTestExtension"]
"""))
@@ -93,7 +93,7 @@ class ExtensionSpec extends WordSpec with Matchers {
}
"log an error if an extension listed in akka.extensions cannot be loaded" in {
- val system = ActorSystem("failing", ConfigFactory.parseString(
+ val system: akka.actor.ActorSystem = ActorSystem("failing", ConfigFactory.parseString(
"""
akka.extensions = ["akka.actor.MissingExtension"]
"""))
@@ -103,8 +103,8 @@ class ExtensionSpec extends WordSpec with Matchers {
}
"allow for auto-loading of library-extensions" in {
- val system = ActorSystem("extensions")
- val listedExtensions = system.settings.config.getStringList("akka.library-extensions")
+ val system: akka.actor.ActorSystem = ActorSystem("extensions")
+ val listedExtensions: java.util.List[String] = system.settings.config.getStringList("akka.library-extensions")
listedExtensions.size should be > 0
// could be initalized by other tests, so at least once
InstanceCountingExtension.createCount.get() should be > 0
diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala
index d55d181..4d30dc7 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala
@@ -15,13 +15,13 @@ import akka.util.Timeout
object FSMActorSpec {
class Latches(implicit system: ActorSystem) {
- val unlockedLatch = TestLatch()
- val lockedLatch = TestLatch()
- val unhandledLatch = TestLatch()
- val terminatedLatch = TestLatch()
- val transitionLatch = TestLatch()
- val initialStateLatch = TestLatch()
- val transitionCallBackLatch = TestLatch()
+ val unlockedLatch: akka.testkit.TestLatch = TestLatch()
+ val lockedLatch: akka.testkit.TestLatch = TestLatch()
+ val unhandledLatch: akka.testkit.TestLatch = TestLatch()
+ val terminatedLatch: akka.testkit.TestLatch = TestLatch()
+ val transitionLatch: akka.testkit.TestLatch = TestLatch()
+ val initialStateLatch: akka.testkit.TestLatch = TestLatch()
+ val transitionCallBackLatch: akka.testkit.TestLatch = TestLatch()
}
sealed trait LockState
@@ -78,7 +78,7 @@ object FSMActorSpec {
// verify that old-style does still compile
onTransition(transitionHandler _)
- def transitionHandler(from: LockState, to: LockState) = {
+ def transitionHandler(from: LockState, to: LockState): Unit = {
// dummy
}
@@ -103,7 +103,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
import FSMActorSpec._
import FSM.`→`
- val timeout = Timeout(2 seconds)
+ val timeout: akka.util.Timeout = Timeout(2 seconds)
"An FSM Actor" must {
@@ -111,14 +111,14 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
import FSM.{ Transition, CurrentState, SubscribeTransitionCallBack }
- val latches = new Latches
+ val latches: akka.actor.FSMActorSpec.Latches = new Latches
import latches._
// lock that locked after being open for 1 sec
- val lock = system.actorOf(Props(new Lock("33221", 1 second, latches)))
+ val lock: akka.actor.ActorRef = system.actorOf(Props(new Lock("33221", 1 second, latches)))
- val transitionTester = system.actorOf(Props(new Actor {
- def receive = {
+ val transitionTester: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Transition(_, _, _) ⇒ transitionCallBackLatch.open
case CurrentState(_, s: LockState) if s eq Locked ⇒ initialStateLatch.open // SI-5900 workaround
}
@@ -143,9 +143,9 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
Await.ready(unhandledLatch, timeout.duration)
}
- val answerLatch = TestLatch()
- val tester = system.actorOf(Props(new Actor {
- def receive = {
+ val answerLatch: akka.testkit.TestLatch = TestLatch()
+ val tester: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Hello ⇒ lock ! "hello"
case "world" ⇒ answerLatch.open
case Bye ⇒ lock ! "bye"
@@ -159,13 +159,13 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
}
"log termination" in {
- val fsm = TestActorRef(new Actor with FSM[Int, Null] {
+ val fsm: akka.testkit.TestActorRef[akka.actor.Actor with akka.actor.FSM[Int, Null]] = TestActorRef(new Actor with FSM[Int, Null] {
startWith(1, null)
when(1) {
case Event("go", _) ⇒ goto(2)
}
})
- val name = fsm.path.toString
+ val name: String = fsm.path.toString
EventFilter.error("Next state 2 does not exist", occurrences = 1) intercept {
system.eventStream.subscribe(testActor, classOf[Logging.Error])
fsm ! "go"
@@ -177,20 +177,20 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
}
"run onTermination upon ActorRef.stop()" in {
- val started = TestLatch(1)
+ val started: akka.testkit.TestLatch = TestLatch(1)
/*
* This lazy val trick is beyond evil: KIDS, DON'T TRY THIS AT HOME!
* It is necessary here because of the path-dependent type fsm.StopEvent.
*/
- lazy val fsm = new Actor with FSM[Int, Null] {
- override def preStart = { started.countDown }
+ lazy val fsm: akka.actor.Actor with akka.actor.FSM[Int, Null] = new Actor with FSM[Int, Null] {
+ override def preStart: Unit = { started.countDown }
startWith(1, null)
when(1) { FSM.NullFunction }
onTermination {
case x ⇒ testActor ! x
}
}
- val ref = system.actorOf(Props(fsm))
+ val ref: akka.actor.ActorRef = system.actorOf(Props(fsm))
Await.ready(started, timeout.duration)
system.stop(ref)
expectMsg(1 second, fsm.StopEvent(FSM.Shutdown, 1, null))
@@ -198,7 +198,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
"run onTermination with updated state upon stop(reason, stateData)" in {
val expected = "pigdog"
- val actor = system.actorOf(Props(new Actor with FSM[Int, String] {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor with FSM[Int, String] {
startWith(1, null)
when(1) {
case Event(2, null) ⇒ stop(FSM.Normal, expected)
@@ -212,10 +212,10 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
}
"cancel all timers when terminated" in {
- val timerNames = List("timer-1", "timer-2", "timer-3")
+ val timerNames: List[String] = List("timer-1", "timer-2", "timer-3")
// Lazy so fsmref can refer to checkTimersActive
- lazy val fsmref = TestFSMRef(new Actor with FSM[String, Null] {
+ lazy val fsmref: akka.testkit.TestFSMRef[String, Null, akka.actor.Actor with akka.actor.FSM[String, Null]] = TestFSMRef(new Actor with FSM[String, Null] {
startWith("not-started", null)
when("not-started") {
case Event("start", _) ⇒ goto("started") replying "starting"
@@ -252,13 +252,13 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
"log events and transitions if asked to do so" in {
import scala.collection.JavaConverters._
- val config = ConfigFactory.parseMap(Map("akka.loglevel" → "DEBUG", "akka.actor.serialize-messages" → "off",
+ val config: com.typesafe.config.Config = ConfigFactory.parseMap(Map("akka.loglevel" → "DEBUG", "akka.actor.serialize-messages" → "off",
"akka.actor.debug.fsm" → true).asJava).withFallback(system.settings.config)
- val fsmEventSystem = ActorSystem("fsmEvent", config)
+ val fsmEventSystem: akka.actor.ActorSystem = ActorSystem("fsmEvent", config)
try {
new TestKit(fsmEventSystem) {
EventFilter.debug(occurrences = 5) intercept {
- val fsm = TestActorRef(new Actor with LoggingFSM[Int, Null] {
+ val fsm: akka.testkit.TestActorRef[akka.actor.Actor with akka.actor.LoggingFSM[Int, Null]] = TestActorRef(new Actor with LoggingFSM[Int, Null] {
startWith(1, null)
when(1) {
case Event("go", _) ⇒
@@ -274,8 +274,8 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
case StopEvent(r, _, _) ⇒ testActor ! r
}
})
- val name = fsm.path.toString
- val fsmClass = fsm.underlyingActor.getClass
+ val name: String = fsm.path.toString
+ val fsmClass: Class[_ <: akka.actor.LoggingFSM[Int, Null]] = fsm.underlyingActor.getClass
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
fsm ! "go"
expectMsgPF(1 second, hint = "processing Event(go,null)") {
@@ -298,7 +298,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
}
"fill rolling event log and hand it out" in {
- val fsmref = TestActorRef(new Actor with LoggingFSM[Int, Int] {
+ val fsmref: akka.testkit.TestActorRef[akka.actor.Actor with akka.actor.LoggingFSM[Int, Int]] = TestActorRef(new Actor with LoggingFSM[Int, Int] {
override def logDepth = 3
startWith(1, 0)
when(1) {
@@ -307,7 +307,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
}
})
fsmref ! "log"
- val fsm = fsmref.underlyingActor
+ val fsm: akka.actor.Actor with akka.actor.LoggingFSM[Int, Int] = fsmref.underlyingActor
import FSM.LogEntry
expectMsg(1 second, IndexedSeq(LogEntry(1, 0, "log")))
fsmref ! "count"
@@ -320,7 +320,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
"allow transforming of state results" in {
import akka.actor.FSM._
- val fsmref = system.actorOf(Props(new Actor with FSM[Int, Int] {
+ val fsmref: akka.actor.ActorRef = system.actorOf(Props(new Actor with FSM[Int, Int] {
startWith(0, 0)
when(0)(transform {
case Event("go", _) ⇒ stay
@@ -338,12 +338,12 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I
}
"allow cancelling stateTimeout by issuing forMax(Duration.Inf)" taggedAs TimingTest in {
- val sys = ActorSystem("fsmEvent")
- val p = TestProbe()(sys)
+ val sys: akka.actor.ActorSystem = ActorSystem("fsmEvent")
+ val p: akka.testkit.TestProbe = TestProbe()(sys)
val OverrideTimeoutToInf = "override-timeout-to-inf"
- val fsm = sys.actorOf(Props(new Actor with FSM[String, String] {
+ val fsm: akka.actor.ActorRef = sys.actorOf(Props(new Actor with FSM[String, String] {
startWith("init", "")
diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala
index 15bfa58..d4e95bb 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala
@@ -13,7 +13,7 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender {
import FSMTimingSpec._
import FSM._
- val fsm = system.actorOf(Props(new StateMachine(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new StateMachine(testActor)))
fsm ! SubscribeTransitionCallBack(testActor)
expectMsg(1 second, CurrentState(fsm, Initial))
@@ -44,7 +44,7 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender {
}
"cancel a StateTimeout when actor is stopped" taggedAs TimingTest in {
- val stoppingActor = system.actorOf(Props[StoppingActor])
+ val stoppingActor: akka.actor.ActorRef = system.actorOf(Props[StoppingActor])
system.eventStream.subscribe(testActor, classOf[DeadLetter])
stoppingActor ! TestStoppingActorStateTimeout
within(400 millis) {
@@ -119,7 +119,7 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender {
"receive and cancel a repeated timer" taggedAs TimingTest in {
fsm ! TestRepeatedTimer
- val seq = receiveWhile(2 seconds) {
+ val seq: scala.collection.immutable.Seq[akka.actor.FSMTimingSpec.Tick.type] = receiveWhile(2 seconds) {
case Tick ⇒ Tick
}
seq should have length 5
diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala
index e9176f9..fec1641 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala
@@ -12,7 +12,7 @@ object FSMTransitionSpec {
import FSM.`→`
class Supervisor extends Actor {
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
class SendAnyTransitionFSM(target: ActorRef) extends Actor with FSM[Int, Int] {
@@ -57,7 +57,7 @@ object FSMTransitionSpec {
}
class Forwarder(target: ActorRef) extends Actor {
- def receive = { case x ⇒ target ! x }
+ def receive: PartialFunction[Any, Unit] = { case x ⇒ target ! x }
}
}
@@ -70,7 +70,7 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
"A FSM transition notifier" must {
"not trigger onTransition for stay" in {
- val fsm = system.actorOf(Props(new SendAnyTransitionFSM(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new SendAnyTransitionFSM(testActor)))
expectMsg(0 → 0) // caused by initialize(), OK.
fsm ! "stay" // no transition event
expectNoMsg(500.millis)
@@ -81,7 +81,7 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
"notify listeners" in {
import FSM.{ CurrentState, SubscribeTransitionCallBack, Transition }
- val fsm = system.actorOf(Props(new MyFSM(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new MyFSM(testActor)))
within(1 second) {
fsm ! SubscribeTransitionCallBack(testActor)
expectMsg(CurrentState(fsm, 0))
@@ -93,8 +93,8 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
}
"not fail when listener goes away" in {
- val forward = system.actorOf(Props(new Forwarder(testActor)))
- val fsm = system.actorOf(Props(new MyFSM(testActor)))
+ val forward: akka.actor.ActorRef = system.actorOf(Props(new Forwarder(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new MyFSM(testActor)))
within(1 second) {
fsm ! FSM.SubscribeTransitionCallBack(forward)
@@ -109,7 +109,7 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
"A FSM" must {
"make previous and next state data available in onTransition" in {
- val fsm = system.actorOf(Props(new OtherFSM(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new OtherFSM(testActor)))
within(1 second) {
fsm ! "tick"
expectMsg((0, 1))
@@ -118,8 +118,8 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
"trigger transition event when goto() the same state" in {
import FSM.Transition
- val forward = system.actorOf(Props(new Forwarder(testActor)))
- val fsm = system.actorOf(Props(new OtherFSM(testActor)))
+ val forward: akka.actor.ActorRef = system.actorOf(Props(new Forwarder(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new OtherFSM(testActor)))
within(1 second) {
fsm ! FSM.SubscribeTransitionCallBack(forward)
@@ -134,8 +134,8 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
}
"not trigger transition event on stay()" in {
- val forward = system.actorOf(Props(new Forwarder(testActor)))
- val fsm = system.actorOf(Props(new OtherFSM(testActor)))
+ val forward: akka.actor.ActorRef = system.actorOf(Props(new Forwarder(testActor)))
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new OtherFSM(testActor)))
within(1 second) {
fsm ! FSM.SubscribeTransitionCallBack(forward)
@@ -146,7 +146,7 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender {
}
"not leak memory in nextState" in {
- val fsmref = system.actorOf(Props(new Actor with FSM[Int, ActorRef] {
+ val fsmref: akka.actor.ActorRef = system.actorOf(Props(new Actor with FSM[Int, ActorRef] {
startWith(0, null)
when(0) {
case Event("switch", _) ⇒ goto(1) using sender()
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala
index feff999..61e4962 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala
@@ -14,13 +14,13 @@ object ForwardActorSpec {
val ExpectedMessage = "FOO"
def createForwardingChain(system: ActorSystem): ActorRef = {
- val replier = system.actorOf(Props(new Actor {
- def receive = { case x ⇒ sender() ! x }
+ val replier: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case x ⇒ sender() ! x }
}))
- def mkforwarder(forwardTo: ActorRef) = system.actorOf(Props(
+ def mkforwarder(forwardTo: ActorRef): akka.actor.ActorRef = system.actorOf(Props(
new Actor {
- def receive = { case x ⇒ forwardTo forward x }
+ def receive: PartialFunction[Any, Unit] = { case x ⇒ forwardTo forward x }
}))
mkforwarder(mkforwarder(mkforwarder(replier)))
@@ -29,20 +29,20 @@ object ForwardActorSpec {
class ForwardActorSpec extends AkkaSpec {
import ForwardActorSpec._
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
"A Forward Actor" must {
"forward actor reference when invoking forward on tell" in {
- val replyTo = system.actorOf(Props(new Actor { def receive = { case ExpectedMessage ⇒ testActor ! ExpectedMessage } }))
+ val replyTo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case ExpectedMessage ⇒ testActor ! ExpectedMessage } }))
- val chain = createForwardingChain(system)
+ val chain: akka.actor.ActorRef = createForwardingChain(system)
chain.tell(ExpectedMessage, replyTo)
expectMsg(5 seconds, ExpectedMessage)
}
"forward actor reference when invoking forward on ask" in {
- val chain = createForwardingChain(system)
+ val chain: akka.actor.ActorRef = createForwardingChain(system)
chain.ask(ExpectedMessage)(5 seconds) pipeTo testActor
expectMsg(5 seconds, ExpectedMessage)
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala
index 112115b..ecba740 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala
@@ -15,20 +15,20 @@ object FunctionRefSpec {
case class Forwarded(msg: Any, sender: ActorRef)
class Super extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case GetForwarder(replyTo) ⇒
- val cell = context.asInstanceOf[ActorCell]
- val ref = cell.addFunctionRef((sender, msg) ⇒ replyTo ! Forwarded(msg, sender))
+ val cell: akka.actor.ActorCell = context.asInstanceOf[ActorCell]
+ val ref: akka.actor.FunctionRef = cell.addFunctionRef((sender, msg) ⇒ replyTo ! Forwarded(msg, sender))
replyTo ! ref
case DropForwarder(ref) ⇒
- val cell = context.asInstanceOf[ActorCell]
+ val cell: akka.actor.ActorCell = context.asInstanceOf[ActorCell]
cell.removeFunctionRef(ref)
}
}
class SupSuper extends Actor {
- val s = context.actorOf(Props[Super], "super")
- def receive = {
+ val s: akka.actor.ActorRef = context.actorOf(Props[Super], "super")
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ s ! msg
}
}
@@ -38,9 +38,9 @@ object FunctionRefSpec {
class FunctionRefSpec extends AkkaSpec with ImplicitSender {
import FunctionRefSpec._
- def commonTests(s: ActorRef) = {
+ def commonTests(s: ActorRef): Unit = {
s ! GetForwarder(testActor)
- val forwarder = expectMsgType[FunctionRef]
+ val forwarder: akka.actor.FunctionRef = expectMsgType[FunctionRef]
"forward messages" in {
forwarder ! "hello"
@@ -49,7 +49,7 @@ class FunctionRefSpec extends AkkaSpec with ImplicitSender {
"be watchable" in {
s ! GetForwarder(testActor)
- val f = expectMsgType[FunctionRef]
+ val f: akka.actor.FunctionRef = expectMsgType[FunctionRef]
watch(f)
s ! DropForwarder(f)
expectTerminated(f)
@@ -57,7 +57,7 @@ class FunctionRefSpec extends AkkaSpec with ImplicitSender {
"be able to watch" in {
s ! GetForwarder(testActor)
- val f = expectMsgType[FunctionRef]
+ val f: akka.actor.FunctionRef = expectMsgType[FunctionRef]
forwarder.watch(f)
s ! DropForwarder(f)
expectMsg(Forwarded(Terminated(f)(true, false), null))
@@ -73,19 +73,19 @@ class FunctionRefSpec extends AkkaSpec with ImplicitSender {
"A FunctionRef" when {
"created by a toplevel actor" must {
- val s = system.actorOf(Props[Super], "super")
+ val s: akka.actor.ActorRef = system.actorOf(Props[Super], "super")
commonTests(s)
}
"created by a non-toplevel actor" must {
- val s = system.actorOf(Props[SupSuper], "supsuper")
+ val s: akka.actor.ActorRef = system.actorOf(Props[SupSuper], "supsuper")
commonTests(s)
}
"not registered" must {
"not be found" in {
- val provider = system.asInstanceOf[ExtendedActorSystem].provider
- val ref = new FunctionRef(testActor.path / "blabla", provider, system.eventStream, (x, y) ⇒ ())
+ val provider: akka.actor.ActorRefProvider = system.asInstanceOf[ExtendedActorSystem].provider
+ val ref: akka.actor.FunctionRef = new FunctionRef(testActor.path / "blabla", provider, system.eventStream, (x, y) ⇒ ())
EventFilter[ClassCastException](occurrences = 1) intercept {
// needs to be something that fails when the deserialized form is not a FunctionRef
// this relies upon serialize-messages during tests
diff --git a/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala
index 4e240ce..244cfb1 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala
@@ -17,27 +17,27 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
"An Actor" must {
"be able to become in its constructor" in {
- val a = system.actorOf(Props(new Becomer {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Becomer {
context.become { case always ⇒ sender() ! always }
- def receive = { case always ⇒ sender() ! "FAILURE" }
+ def receive: PartialFunction[Any, Unit] = { case always ⇒ sender() ! "FAILURE" }
}))
a ! "pigdog"
expectMsg("pigdog")
}
"be able to become multiple times in its constructor" in {
- val a = system.actorOf(Props(new Becomer {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Becomer {
for (i ← 1 to 4) context.become({ case always ⇒ sender() ! i + ":" + always })
- def receive = { case always ⇒ sender() ! "FAILURE" }
+ def receive: PartialFunction[Any, Unit] = { case always ⇒ sender() ! "FAILURE" }
}))
a ! "pigdog"
expectMsg("4:pigdog")
}
"be able to become with stacking in its constructor" in {
- val a = system.actorOf(Props(new Becomer {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Becomer {
context.become({ case always ⇒ sender() ! "pigdog:" + always; context.unbecome() }, false)
- def receive = { case always ⇒ sender() ! "badass:" + always }
+ def receive: PartialFunction[Any, Unit] = { case always ⇒ sender() ! "badass:" + always }
}))
a ! "pigdog"
expectMsg("pigdog:pigdog")
@@ -46,9 +46,9 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
}
"be able to become, with stacking, multiple times in its constructor" in {
- val a = system.actorOf(Props(new Becomer {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Becomer {
for (i ← 1 to 4) context.become({ case always ⇒ sender() ! i + ":" + always; context.unbecome() }, false)
- def receive = { case always ⇒ sender() ! "FAILURE" }
+ def receive: PartialFunction[Any, Unit] = { case always ⇒ sender() ! "FAILURE" }
}))
a ! "pigdog"
a ! "pigdog"
@@ -61,8 +61,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
}
"be able to hotswap its behavior with become(..)" in {
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "init" ⇒ sender() ! "init"
case "swap" ⇒ context.become({ case x: String ⇒ context.sender() ! x })
}
@@ -76,8 +76,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
}
"be able to revert hotswap its behavior with unbecome" in {
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "init" ⇒ sender() ! "init"
case "swap" ⇒ context.become({
case "swapped" ⇒ sender() ! "swapped"
@@ -100,8 +100,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
"revert to initial state on restart" in {
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "state" ⇒ sender() ! "0"
case "swap" ⇒
context.become({
diff --git a/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala
index b85df41..1bbbc66 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala
@@ -34,23 +34,23 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
"An LocalActorRefProvider" must {
"find actor refs using actorFor" in {
- val a = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } }))
- val b = system.actorFor(a.path)
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case _ ⇒ } }))
+ val b: akka.actor.ActorRef = system.actorFor(a.path)
a should ===(b)
}
"find child actor with URL encoded name using actorFor" in {
val childName = "akka%3A%2F%2FClusterSystem%40127.0.0.1%3A2552"
- val a = system.actorOf(Props(new Actor {
- val child = context.actorOf(Props.empty, name = childName)
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ val child: akka.actor.ActorRef = context.actorOf(Props.empty, name = childName)
+ def receive: PartialFunction[Any, Unit] = {
case "lookup" ⇒
if (childName == child.path.name) sender() ! context.actorFor(childName)
else sender() ! s"$childName is not ${child.path.name}!"
}
}))
a.tell("lookup", testActor)
- val b = expectMsgType[ActorRef]
+ val b: akka.actor.ActorRef = expectMsgType[ActorRef]
b.isTerminated should ===(false)
b.path.name should ===(childName)
}
@@ -62,8 +62,8 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
"not handle messages other than those it will act upon" in {
val message = "Hello, Mr. Root Guardian"
- val rootGuardian = system.actorSelection("/")
- val deadLettersPath = system.deadLetters.path
+ val rootGuardian: akka.actor.ActorSelection = system.actorSelection("/")
+ val deadLettersPath: akka.actor.ActorPath = system.deadLetters.path
filterEvents(EventFilter.warning(s"unhandled message from Actor[$deadLettersPath]: $message", occurrences = 1)) {
rootGuardian ! message
@@ -75,8 +75,8 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
"not handle messages other than those it will act upon" in {
val message = "Hello, Mr. User Guardian"
- val userGuardian = system.actorSelection("/user")
- val deadLettersPath = system.deadLetters.path
+ val userGuardian: akka.actor.ActorSelection = system.actorSelection("/user")
+ val deadLettersPath: akka.actor.ActorPath = system.deadLetters.path
filterEvents(EventFilter.warning(s"unhandled message from Actor[$deadLettersPath]: $message", occurrences = 1)) {
userGuardian ! message
@@ -88,8 +88,8 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
"not handle messages other than those it will act upon" in {
val message = "Hello, Mr. System Guardian"
- val systemGuardian = system.actorSelection("/system")
- val deadLettersPath = system.deadLetters.path
+ val systemGuardian: akka.actor.ActorSelection = system.actorSelection("/system")
+ val deadLettersPath: akka.actor.ActorPath = system.deadLetters.path
filterEvents(EventFilter.warning(s"unhandled message from Actor[$deadLettersPath]: $message", occurrences = 1)) {
systemGuardian ! message
@@ -100,20 +100,20 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
"A LocalActorRef's ActorCell" must {
"not retain its original Props when terminated" in {
val GetChild = "GetChild"
- val a = watch(system.actorOf(Props(new Actor {
- val child = context.actorOf(Props.empty)
- def receive = { case `GetChild` ⇒ sender() ! child }
+ val a: akka.actor.ActorRef = watch(system.actorOf(Props(new Actor {
+ val child: akka.actor.ActorRef = context.actorOf(Props.empty)
+ def receive: PartialFunction[Any, Unit] = { case `GetChild` ⇒ sender() ! child }
})))
a.tell(GetChild, testActor)
- val child = expectMsgType[ActorRef]
- val childProps1 = child.asInstanceOf[LocalActorRef].underlying.props
+ val child: akka.actor.ActorRef = expectMsgType[ActorRef]
+ val childProps1: akka.actor.Props = child.asInstanceOf[LocalActorRef].underlying.props
childProps1 should ===(Props.empty)
system stop a
expectTerminated(a)
// the fields are cleared after the Terminated message has been sent,
// so we need to check for a reasonable time after we receive it
awaitAssert({
- val childProps2 = child.asInstanceOf[LocalActorRef].underlying.props
+ val childProps2: akka.actor.Props = child.asInstanceOf[LocalActorRef].underlying.props
childProps2 should not be theSameInstanceAs(childProps1)
childProps2 should be theSameInstanceAs ActorCell.terminatedProps
}, 1 second)
@@ -121,18 +121,18 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
}
"An ActorRefFactory" must {
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
"only create one instance of an actor with a specific address in a concurrent environment" in {
- val impl = system.asInstanceOf[ActorSystemImpl]
- val provider = impl.provider
+ val impl: akka.actor.ActorSystemImpl = system.asInstanceOf[ActorSystemImpl]
+ val provider: akka.actor.ActorRefProvider = impl.provider
provider.isInstanceOf[LocalActorRefProvider] should ===(true)
for (i ← 0 until 100) {
- val address = "new-actor" + i
- implicit val timeout = Timeout(5 seconds)
- val actors = for (j ← 1 to 4) yield Future(system.actorOf(Props(new Actor { def receive = { case _ ⇒ } }), address))
- val set = Set() ++ actors.map(a ⇒ Await.ready(a, timeout.duration).value match {
+ val address: String = "new-actor" + i
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
+ val actors: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[akka.actor.ActorRef]] = for (j ← 1 to 4) yield Future(system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case _ ⇒ } }), address))
+ val set: scala.collection.immutable.Set[Any] = Set() ++ actors.map(a ⇒ Await.ready(a, timeout.duration).value match {
case Some(Success(a: ActorRef)) ⇒ 1
case Some(Failure(ex: InvalidActorNameException)) ⇒ 2
case x ⇒ x
@@ -142,8 +142,8 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi
}
"only create one instance of an actor from within the same message invocation" in {
- val supervisor = system.actorOf(Props(new Actor {
- def receive = {
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "" ⇒
val a, b = context.actorOf(Props.empty, "duplicate")
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/PropsCreationSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/PropsCreationSpec.scala
index cb3538a..0119c2e 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/PropsCreationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/PropsCreationSpec.scala
@@ -12,11 +12,11 @@ object PropsCreationSpec {
final class B
class OneParamActor(blackhole: A) extends Actor {
- override def receive = Actor.emptyBehavior
+ override def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}
class TwoParamActor(blackhole1: A, blackhole2: B) extends Actor {
- override def receive = Actor.emptyBehavior
+ override def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}
object OneParamActorCreator extends akka.japi.Creator[Actor] {
@@ -31,30 +31,30 @@ class PropsCreationSpec extends AkkaSpec("akka.actor.serialize-creators = on") {
"Props" must {
"work with creator" in {
- val p = Props(new OneParamActor(null))
+ val p: akka.actor.Props = Props(new OneParamActor(null))
system.actorOf(p)
}
"work with classOf" in {
- val p = Props(classOf[OneParamActor], null)
+ val p: akka.actor.Props = Props(classOf[OneParamActor], null)
system.actorOf(p)
}
"work with classOf + 1 `null` param" in {
- val p = Props(classOf[OneParamActor], null)
+ val p: akka.actor.Props = Props(classOf[OneParamActor], null)
system.actorOf(p)
}
"work with classOf + 2 `null` params" in {
- val p = Props(classOf[TwoParamActor], null, null)
+ val p: akka.actor.Props = Props(classOf[TwoParamActor], null, null)
system.actorOf(p)
}
}
"Props Java API" must {
"work with create(creator)" in {
- val p = Props.create(OneParamActorCreator)
+ val p: akka.actor.Props = Props.create(OneParamActorCreator)
system.actorOf(p)
}
"work with create(class, param)" in {
- val p = Props.create(classOf[OneParamActor], null)
+ val p: akka.actor.Props = Props.create(classOf[OneParamActor], null)
system.actorOf(p)
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala
index bd2cd30..3754bf9 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala
@@ -22,12 +22,12 @@ class ReceiveTimeoutSpec extends AkkaSpec {
"An actor with receive timeout" must {
"get timeout" taggedAs TimingTest in {
- val timeoutLatch = TestLatch()
+ val timeoutLatch: akka.testkit.TestLatch = TestLatch()
- val timeoutActor = system.actorOf(Props(new Actor {
+ val timeoutActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case ReceiveTimeout ⇒ timeoutLatch.open
}
}))
@@ -37,12 +37,12 @@ class ReceiveTimeoutSpec extends AkkaSpec {
}
"reschedule timeout after regular receive" taggedAs TimingTest in {
- val timeoutLatch = TestLatch()
+ val timeoutLatch: akka.testkit.TestLatch = TestLatch()
- val timeoutActor = system.actorOf(Props(new Actor {
+ val timeoutActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Tick ⇒ ()
case ReceiveTimeout ⇒ timeoutLatch.open
}
@@ -55,13 +55,13 @@ class ReceiveTimeoutSpec extends AkkaSpec {
}
"be able to turn off timeout if desired" taggedAs TimingTest in {
- val count = new AtomicInteger(0)
- val timeoutLatch = TestLatch()
+ val count: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val timeoutLatch: akka.testkit.TestLatch = TestLatch()
- val timeoutActor = system.actorOf(Props(new Actor {
+ val timeoutActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.setReceiveTimeout(500 milliseconds)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Tick ⇒ ()
case ReceiveTimeout ⇒
count.incrementAndGet
@@ -78,10 +78,10 @@ class ReceiveTimeoutSpec extends AkkaSpec {
}
"not receive timeout message when not specified" taggedAs TimingTest in {
- val timeoutLatch = TestLatch()
+ val timeoutLatch: akka.testkit.TestLatch = TestLatch()
- val timeoutActor = system.actorOf(Props(new Actor {
- def receive = {
+ val timeoutActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case ReceiveTimeout ⇒ timeoutLatch.open
}
}))
@@ -91,19 +91,19 @@ class ReceiveTimeoutSpec extends AkkaSpec {
}
"get timeout while receiving NotInfluenceReceiveTimeout messages" taggedAs TimingTest in {
- val timeoutLatch = TestLatch()
+ val timeoutLatch: akka.testkit.TestLatch = TestLatch()
- val timeoutActor = system.actorOf(Props(new Actor {
+ val timeoutActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.setReceiveTimeout(1 second)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case ReceiveTimeout ⇒ timeoutLatch.open
case TransperentTick ⇒
}
}))
- val ticks = system.scheduler.schedule(100.millis, 100.millis, new Runnable {
- override def run() = {
+ val ticks: akka.actor.Cancellable = system.scheduler.schedule(100.millis, 100.millis, new Runnable {
+ override def run(): Unit = {
timeoutActor ! TransperentTick
timeoutActor ! Identify(None)
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/RelativeActorPathSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/RelativeActorPathSpec.scala
index f6c06b8..440c0b2 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/RelativeActorPathSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/RelativeActorPathSpec.scala
@@ -20,7 +20,7 @@ class RelativeActorPathSpec extends WordSpec with Matchers {
elements("foo/bar/baz") should ===(List("foo", "bar", "baz"))
}
"match url encoded name" in {
- val name = URLEncoder.encode("akka://[email protected]:2552", "UTF-8")
+ val name: String = URLEncoder.encode("akka://[email protected]:2552", "UTF-8")
elements(name) should ===(List(name))
}
"match path with uid fragment" in {
diff --git a/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala
index d09d25f..bc1731f 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala
@@ -28,33 +28,33 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off"
"A RestartStrategy" must {
"ensure that slave stays dead after max restarts within time range" in {
- val boss = system.actorOf(Props(new Supervisor(
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 1 second)(List(classOf[Throwable])))))
- val restartLatch = new TestLatch
- val secondRestartLatch = new TestLatch
- val countDownLatch = new TestLatch(3)
- val stopLatch = new TestLatch
+ val restartLatch: akka.testkit.TestLatch = new TestLatch
+ val secondRestartLatch: akka.testkit.TestLatch = new TestLatch
+ val countDownLatch: akka.testkit.TestLatch = new TestLatch(3)
+ val stopLatch: akka.testkit.TestLatch = new TestLatch
- val slaveProps = Props(new Actor {
+ val slaveProps: akka.actor.Props = Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒ countDownLatch.countDown()
case Crash ⇒ throw new Exception("Crashing...")
}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
if (!restartLatch.isOpen)
restartLatch.open()
else
secondRestartLatch.open()
}
- override def postStop() = {
+ override def postStop(): Unit = {
stopLatch.open()
}
})
- val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
+ val slave: akka.actor.ActorRef = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
slave ! Ping
slave ! Crash
@@ -75,21 +75,21 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off"
}
"ensure that slave is immortal without max restarts and time range" in {
- val boss = system.actorOf(Props(new Supervisor(OneForOneStrategy()(List(classOf[Throwable])))))
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(OneForOneStrategy()(List(classOf[Throwable])))))
- val countDownLatch = new TestLatch(100)
+ val countDownLatch: akka.testkit.TestLatch = new TestLatch(100)
- val slaveProps = Props(new Actor {
+ val slaveProps: akka.actor.Props = Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Crash ⇒ throw new Exception("Crashing...")
}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
countDownLatch.countDown()
}
})
- val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
+ val slave: akka.actor.ActorRef = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
(1 to 100) foreach { _ ⇒ slave ! Crash }
Await.ready(countDownLatch, 2 minutes)
@@ -97,23 +97,23 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off"
}
"ensure that slave restarts after number of crashes not within time range" in {
- val boss = system.actorOf(Props(new Supervisor(
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 2, withinTimeRange = 500 millis)(List(classOf[Throwable])))))
- val restartLatch = new TestLatch
- val secondRestartLatch = new TestLatch
- val thirdRestartLatch = new TestLatch
- val pingLatch = new TestLatch
- val secondPingLatch = new TestLatch
+ val restartLatch: akka.testkit.TestLatch = new TestLatch
+ val secondRestartLatch: akka.testkit.TestLatch = new TestLatch
+ val thirdRestartLatch: akka.testkit.TestLatch = new TestLatch
+ val pingLatch: akka.testkit.TestLatch = new TestLatch
+ val secondPingLatch: akka.testkit.TestLatch = new TestLatch
- val slaveProps = Props(new Actor {
+ val slaveProps: akka.actor.Props = Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒
if (!pingLatch.isOpen) pingLatch.open else secondPingLatch.open
case Crash ⇒ throw new Exception("Crashing...")
}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
if (!restartLatch.isOpen)
restartLatch.open()
else if (!secondRestartLatch.isOpen)
@@ -122,13 +122,13 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off"
thirdRestartLatch.open()
}
- override def postStop() = {
+ override def postStop(): Unit = {
if (restartLatch.isOpen) {
secondRestartLatch.open()
}
}
})
- val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
+ val slave: akka.actor.ActorRef = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
slave ! Ping
slave ! Crash
@@ -155,31 +155,31 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off"
}
"ensure that slave is not restarted after max retries" in {
- val boss = system.actorOf(Props(new Supervisor(OneForOneStrategy(maxNrOfRetries = 2)(List(classOf[Throwable])))))
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(OneForOneStrategy(maxNrOfRetries = 2)(List(classOf[Throwable])))))
- val restartLatch = new TestLatch
- val secondRestartLatch = new TestLatch
- val countDownLatch = new TestLatch(3)
- val stopLatch = new TestLatch
+ val restartLatch: akka.testkit.TestLatch = new TestLatch
+ val secondRestartLatch: akka.testkit.TestLatch = new TestLatch
+ val countDownLatch: akka.testkit.TestLatch = new TestLatch(3)
+ val stopLatch: akka.testkit.TestLatch = new TestLatch
- val slaveProps = Props(new Actor {
+ val slaveProps: akka.actor.Props = Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒ countDownLatch.countDown()
case Crash ⇒ throw new Exception("Crashing...")
}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
if (!restartLatch.isOpen)
restartLatch.open()
else
secondRestartLatch.open()
}
- override def postStop() = {
+ override def postStop(): Unit = {
stopLatch.open()
}
})
- val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
+ val slave: akka.actor.ActorRef = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
slave ! Ping
slave ! Crash
@@ -207,32 +207,32 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off"
"ensure that slave is not restarted within time range" in {
val restartLatch, stopLatch, maxNoOfRestartsLatch = new TestLatch
- val countDownLatch = new TestLatch(2)
+ val countDownLatch: akka.testkit.TestLatch = new TestLatch(2)
- val boss = system.actorOf(Props(new Actor {
- override val supervisorStrategy = OneForOneStrategy(withinTimeRange = 1 second)(List(classOf[Throwable]))
- def receive = {
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy(withinTimeRange = 1 second)(List(classOf[Throwable]))
+ def receive: PartialFunction[Any, Unit] = {
case p: Props ⇒ sender() ! context.watch(context.actorOf(p))
case t: Terminated ⇒ maxNoOfRestartsLatch.open()
}
}))
- val slaveProps = Props(new Actor {
+ val slaveProps: akka.actor.Props = Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒ countDownLatch.countDown()
case Crash ⇒ throw new Exception("Crashing...")
}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
restartLatch.open()
}
- override def postStop() = {
+ override def postStop(): Unit = {
stopLatch.open()
}
})
- val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
+ val slave: akka.actor.ActorRef = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration)
slave ! Ping
slave ! Crash
diff --git a/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala
index a7197cf..028367e 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala
@@ -20,7 +20,7 @@ import akka.testkit._
import scala.util.control.NoStackTrace
object SchedulerSpec {
- val testConfRevolver = ConfigFactory.parseString("""
+ val testConfRevolver: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.scheduler.implementation = akka.actor.LightArrayRevolverScheduler
akka.scheduler.ticks-per-wheel = 32
akka.actor.serialize-messages = off
@@ -40,7 +40,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
val tickActor, tickActor2 = system.actorOf(Props(new Actor {
var ticks = 0
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Tick ⇒
if (ticks < 3) {
sender() ! Tock
@@ -67,7 +67,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"stop continuous scheduling if the receiving actor has been terminated" taggedAs TimingTest in {
- val actor = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } }))
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ sender() ! x } }))
// run immediately and then every 100 milliseconds
collectCancellable(system.scheduler.schedule(0 milliseconds, 100 milliseconds, actor, "msg"))
@@ -80,9 +80,9 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"stop continuous scheduling if the task throws exception" taggedAs TimingTest in {
- val count = new AtomicInteger(0)
+ val count: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
collectCancellable(system.scheduler.schedule(0 milliseconds, 20.millis) {
- val c = count.incrementAndGet()
+ val c: Int = count.incrementAndGet()
testActor ! c
if (c == 3) throw new RuntimeException("TEST") with NoStackTrace
})
@@ -94,9 +94,9 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
"schedule once" taggedAs TimingTest in {
case object Tick
- val countDownLatch = new CountDownLatch(3)
- val tickActor = system.actorOf(Props(new Actor {
- def receive = { case Tick ⇒ countDownLatch.countDown() }
+ val countDownLatch: java.util.concurrent.CountDownLatch = new CountDownLatch(3)
+ val tickActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case Tick ⇒ countDownLatch.countDown() }
}))
// run after 300 millisec
@@ -123,11 +123,11 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"be cancellable during initial delay" taggedAs TimingTest in {
- val ticks = new AtomicInteger
+ val ticks: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
- val initialDelay = 200.milliseconds.dilated
- val delay = 10.milliseconds.dilated
- val timeout = collectCancellable(system.scheduler.schedule(initialDelay, delay) {
+ val initialDelay: scala.concurrent.duration.FiniteDuration = 200.milliseconds.dilated
+ val delay: scala.concurrent.duration.FiniteDuration = 10.milliseconds.dilated
+ val timeout: akka.actor.Cancellable = collectCancellable(system.scheduler.schedule(initialDelay, delay) {
ticks.incrementAndGet()
})
Thread.sleep(10.milliseconds.dilated.toMillis)
@@ -138,11 +138,11 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"be cancellable after initial delay" taggedAs TimingTest in {
- val ticks = new AtomicInteger
+ val ticks: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
- val initialDelay = 90.milliseconds.dilated
- val delay = 500.milliseconds.dilated
- val timeout = collectCancellable(system.scheduler.schedule(initialDelay, delay) {
+ val initialDelay: scala.concurrent.duration.FiniteDuration = 90.milliseconds.dilated
+ val delay: scala.concurrent.duration.FiniteDuration = 500.milliseconds.dilated
+ val timeout: akka.actor.Cancellable = collectCancellable(system.scheduler.schedule(initialDelay, delay) {
ticks.incrementAndGet()
})
Thread.sleep((initialDelay + 200.milliseconds.dilated).toMillis)
@@ -153,7 +153,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"be canceled if cancel is performed before execution" taggedAs TimingTest in {
- val task = collectCancellable(system.scheduler.scheduleOnce(10 seconds)(()))
+ val task: akka.actor.Cancellable = collectCancellable(system.scheduler.scheduleOnce(10 seconds)(()))
task.cancel() should ===(true)
task.isCancelled should ===(true)
task.cancel() should ===(false)
@@ -161,8 +161,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"not be canceled if cancel is performed after execution" taggedAs TimingTest in {
- val latch = TestLatch(1)
- val task = collectCancellable(system.scheduler.scheduleOnce(10 millis)(latch.countDown()))
+ val latch: akka.testkit.TestLatch = TestLatch(1)
+ val task: akka.actor.Cancellable = collectCancellable(system.scheduler.scheduleOnce(10 millis)(latch.countDown()))
Await.ready(latch, remainingOrDefault)
task.cancel() should ===(false)
task.isCancelled should ===(false)
@@ -178,19 +178,19 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
object Ping
object Crash
- val restartLatch = new TestLatch
- val pingLatch = new TestLatch(6)
+ val restartLatch: akka.testkit.TestLatch = new TestLatch
+ val pingLatch: akka.testkit.TestLatch = new TestLatch(6)
- val supervisor = system.actorOf(Props(new Supervisor(AllForOneStrategy(3, 1 second)(List(classOf[Exception])))))
- val props = Props(new Actor {
- def receive = {
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(AllForOneStrategy(3, 1 second)(List(classOf[Exception])))))
+ val props: akka.actor.Props = Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒ pingLatch.countDown()
case Crash ⇒ throw new Exception("CRASH")
}
- override def postRestart(reason: Throwable) = restartLatch.open
+ override def postRestart(reason: Throwable): Unit = restartLatch.open
})
- val actor = Await.result((supervisor ? props).mapTo[ActorRef], timeout.duration)
+ val actor: akka.actor.ActorRef = Await.result((supervisor ? props).mapTo[ActorRef], timeout.duration)
collectCancellable(system.scheduler.schedule(500 milliseconds, 500 milliseconds, actor, Ping))
// appx 2 pings before crash
@@ -204,14 +204,14 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"never fire prematurely" taggedAs TimingTest in {
- val ticks = new TestLatch(300)
+ val ticks: akka.testkit.TestLatch = new TestLatch(300)
final case class Msg(ts: Long)
- val actor = system.actorOf(Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Msg(ts) ⇒
- val now = System.nanoTime
+ val now: Long = System.nanoTime
// Make sure that no message has been dispatched before the scheduled time (10ms) has occurred
if (now < ts) throw new RuntimeException("Interval is too small: " + (now - ts))
ticks.countDown()
@@ -227,15 +227,15 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"schedule with different initial delay and frequency" taggedAs TimingTest in {
- val ticks = new TestLatch(3)
+ val ticks: akka.testkit.TestLatch = new TestLatch(3)
case object Msg
- val actor = system.actorOf(Props(new Actor {
- def receive = { case Msg ⇒ ticks.countDown() }
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case Msg ⇒ ticks.countDown() }
}))
- val startTime = System.nanoTime()
+ val startTime: Long = System.nanoTime()
collectCancellable(system.scheduler.schedule(1 second, 300 milliseconds, actor, Msg))
Await.ready(ticks, 3 seconds)
@@ -246,9 +246,9 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"adjust for scheduler inaccuracy" taggedAs TimingTest in {
- val startTime = System.nanoTime
+ val startTime: Long = System.nanoTime
val n = 200
- val latch = new TestLatch(n)
+ val latch: akka.testkit.TestLatch = new TestLatch(n)
system.scheduler.schedule(25.millis, 25.millis) { latch.countDown() }
Await.ready(latch, 6.seconds)
// Rate
@@ -257,8 +257,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
"not be affected by long running task" taggedAs TimingTest in {
val n = 22
- val latch = new TestLatch(n)
- val startTime = System.nanoTime
+ val latch: akka.testkit.TestLatch = new TestLatch(n)
+ val startTime: Long = System.nanoTime
system.scheduler.schedule(225.millis, 225.millis) {
Thread.sleep(100)
latch.countDown()
@@ -269,10 +269,10 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"handle timeouts equal to multiple of wheel period" taggedAs TimingTest in {
- val timeout = 3200 milliseconds
- val barrier = TestLatch()
+ val timeout: scala.concurrent.duration.FiniteDuration = 3200 milliseconds
+ val barrier: akka.testkit.TestLatch = TestLatch()
import system.dispatcher
- val job = system.scheduler.scheduleOnce(timeout)(barrier.countDown())
+ val job: akka.actor.Cancellable = system.scheduler.scheduleOnce(timeout)(barrier.countDown())
try {
Await.ready(barrier, 5000 milliseconds)
} finally {
@@ -281,22 +281,22 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
}
"survive being stressed without cancellation" taggedAs TimingTest in {
- val r = ThreadLocalRandom.current()
+ val r: java.util.concurrent.ThreadLocalRandom = ThreadLocalRandom.current()
val N = 100000
for (_ ← 1 to N) {
- val next = r.nextInt(3000)
- val now = System.nanoTime
+ val next: Int = r.nextInt(3000)
+ val now: Long = System.nanoTime
system.scheduler.scheduleOnce(next.millis) {
- val stop = System.nanoTime
+ val stop: Long = System.nanoTime
testActor ! (stop - now - next * 1000000L)
}
}
- val latencies = within(10.seconds) {
+ val latencies: scala.collection.immutable.IndexedSeq[Long] = within(10.seconds) {
for (i ← 1 to N) yield try expectMsgType[Long] catch {
case NonFatal(e) ⇒ throw new Exception(s"failed expecting the $i-th latency", e)
}
}
- val histogram = latencies groupBy (_ / 100000000L)
+ val histogram: scala.collection.immutable.Map[Long, scala.collection.immutable.IndexedSeq[Long]] = latencies groupBy (_ / 100000000L)
for (k ← histogram.keys.toSeq.sorted) {
system.log.info(f"${k * 100}%3d: ${histogram(k).size}")
}
@@ -308,12 +308,12 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
def collectCancellable(c: Cancellable): Cancellable = c
- def tickDuration = system.scheduler.asInstanceOf[LightArrayRevolverScheduler].TickDuration
+ def tickDuration: scala.concurrent.duration.FiniteDuration = system.scheduler.asInstanceOf[LightArrayRevolverScheduler].TickDuration
"A LightArrayRevolverScheduler" must {
"reject tasks scheduled too far into the future" taggedAs TimingTest in {
- val maxDelay = tickDuration * Int.MaxValue
+ val maxDelay: scala.concurrent.duration.FiniteDuration = tickDuration * Int.MaxValue
import system.dispatcher
system.scheduler.scheduleOnce(maxDelay, testActor, "OK")
intercept[IllegalArgumentException] {
@@ -322,7 +322,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
}
"reject periodic tasks scheduled too far into the future" taggedAs TimingTest in {
- val maxDelay = tickDuration * Int.MaxValue
+ val maxDelay: scala.concurrent.duration.FiniteDuration = tickDuration * Int.MaxValue
import system.dispatcher
system.scheduler.schedule(maxDelay, 1.second, testActor, "OK")
intercept[IllegalArgumentException] {
@@ -331,7 +331,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
}
"reject periodic tasks scheduled with too long interval" taggedAs TimingTest in {
- val maxDelay = tickDuration * Int.MaxValue
+ val maxDelay: scala.concurrent.duration.FiniteDuration = tickDuration * Int.MaxValue
import system.dispatcher
system.scheduler.schedule(100.millis, maxDelay, testActor, "OK")
expectMsg("OK")
@@ -343,30 +343,30 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"survive being stressed with cancellation" taggedAs TimingTest in {
import system.dispatcher
- val r = ThreadLocalRandom.current
+ val r: java.util.concurrent.ThreadLocalRandom = ThreadLocalRandom.current
val N = 1000000
- val tasks = for (_ ← 1 to N) yield {
- val next = r.nextInt(3000)
- val now = System.nanoTime
+ val tasks: scala.collection.immutable.IndexedSeq[akka.actor.Cancellable] = for (_ ← 1 to N) yield {
+ val next: Int = r.nextInt(3000)
+ val now: Long = System.nanoTime
system.scheduler.scheduleOnce(next.millis) {
- val stop = System.nanoTime
+ val stop: Long = System.nanoTime
testActor ! (stop - now - next * 1000000L)
}
}
// get somewhat into the middle of things
Thread.sleep(500)
- val cancellations = for (t ← tasks) yield {
+ val cancellations: scala.collection.immutable.IndexedSeq[Int] = for (t ← tasks) yield {
t.cancel()
if (t.isCancelled) 1 else 0
}
- val cancelled = cancellations.sum
+ val cancelled: Int = cancellations.sum
println(cancelled)
- val latencies = within(10.seconds) {
+ val latencies: scala.collection.immutable.IndexedSeq[Long] = within(10.seconds) {
for (i ← 1 to (N - cancelled)) yield try expectMsgType[Long] catch {
case NonFatal(e) ⇒ throw new Exception(s"failed expecting the $i-th latency", e)
}
}
- val histogram = latencies groupBy (_ / 100000000L)
+ val histogram: scala.collection.immutable.Map[Long, scala.collection.immutable.IndexedSeq[Long]] = latencies groupBy (_ / 100000000L)
for (k ← histogram.keys.toSeq.sorted) {
system.log.info(f"${k * 100}%3d: ${histogram(k).size}")
}
@@ -377,8 +377,8 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
withScheduler(config = ConfigFactory.parseString("akka.scheduler.ticks-per-wheel=2")) { (sched, driver) ⇒
import driver._
import system.dispatcher
- val counter = new AtomicInteger
- val terminated = future {
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val terminated: scala.concurrent.Future[Int] = future {
var rounds = 0
while (Try(sched.scheduleOnce(Duration.Zero)(())(localEC)).isSuccess) {
Thread.sleep(1)
@@ -387,7 +387,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
}
rounds
}
- def delay = if (ThreadLocalRandom.current.nextBoolean) step * 2 else step
+ def delay: scala.concurrent.duration.FiniteDuration = if (ThreadLocalRandom.current.nextBoolean) step * 2 else step
val N = 1000000
(1 to N) foreach (_ ⇒ sched.scheduleOnce(delay)(counter.incrementAndGet()))
sched.close()
@@ -398,9 +398,9 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"execute multiple jobs at once when expiring multiple buckets" taggedAs TimingTest in {
withScheduler() { (sched, driver) ⇒
- implicit def ec = localEC
+ implicit def ec: scala.concurrent.ExecutionContext = localEC
import driver._
- val start = step / 2
+ val start: scala.concurrent.duration.FiniteDuration = step / 2
(0 to 3) foreach (i ⇒ sched.scheduleOnce(start + step * i, testActor, "hello"))
expectNoMsg(step)
wakeUp(step)
@@ -413,7 +413,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"properly defer jobs even when the timer thread oversleeps" taggedAs TimingTest in {
withScheduler() { (sched, driver) ⇒
- implicit def ec = localEC
+ implicit def ec: scala.concurrent.ExecutionContext = localEC
import driver._
sched.scheduleOnce(step * 3, probe.ref, "hello")
wakeUp(step * 5)
@@ -428,9 +428,9 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"correctly wrap around wheel rounds" taggedAs TimingTest in {
withScheduler(config = ConfigFactory.parseString("akka.scheduler.ticks-per-wheel=2")) { (sched, driver) ⇒
- implicit def ec = localEC
+ implicit def ec: scala.concurrent.ExecutionContext = localEC
import driver._
- val start = step / 2
+ val start: scala.concurrent.duration.FiniteDuration = step / 2
(0 to 3) foreach (i ⇒ sched.scheduleOnce(start + step * i, probe.ref, "hello"))
probe.expectNoMsg(step)
wakeUp(step)
@@ -455,9 +455,9 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"correctly execute jobs when clock wraps around" taggedAs TimingTest in {
withScheduler(Long.MaxValue - 200000000L) { (sched, driver) ⇒
- implicit def ec = localEC
+ implicit def ec: scala.concurrent.ExecutionContext = localEC
import driver._
- val start = step / 2
+ val start: scala.concurrent.duration.FiniteDuration = step / 2
(0 to 3) foreach (i ⇒ sched.scheduleOnce(start + step * i, testActor, "hello"))
expectNoMsg(step)
wakeUp(step)
@@ -482,18 +482,18 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"correctly wrap around ticks" taggedAs TimingTest in {
val numEvents = 40
- val targetTicks = Int.MaxValue - numEvents + 20
+ val targetTicks: Int = Int.MaxValue - numEvents + 20
withScheduler(_startTick = Int.MaxValue - 100) { (sched, driver) ⇒
- implicit def ec = localEC
+ implicit def ec: scala.concurrent.ExecutionContext = localEC
import driver._
- val start = step / 2
+ val start: scala.concurrent.duration.FiniteDuration = step / 2
wakeUp(step * targetTicks)
probe.expectMsgType[Long]
- val nums = 0 until numEvents
+ val nums: scala.collection.immutable.Range = 0 until numEvents
nums foreach (i ⇒ sched.scheduleOnce(start + step * i, testActor, "hello-" + i))
expectNoMsg(step)
wakeUp(step)
@@ -510,7 +510,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
"reliably reject jobs when shutting down" taggedAs TimingTest in {
withScheduler() { (sched, driver) ⇒
import system.dispatcher
- val counter = new AtomicInteger
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
future { Thread.sleep(5); driver.close(); sched.close() }
val headroom = 200
var overrun = headroom
@@ -520,7 +520,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
.take(cap)
.takeWhile(_.isSuccess || { overrun -= 1; overrun >= 0 })
.partition(_.isSuccess)
- val s = success.size
+ val s: Int = success.size
s should be < cap
awaitCond(s == counter.get, message = s"$s was not ${counter.get}")
failure.size should ===(headroom)
@@ -537,18 +537,18 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
def close(): Unit
}
- val localEC = new ExecutionContext {
+ val localEC: scala.concurrent.ExecutionContext = new ExecutionContext {
def execute(runnable: Runnable) { runnable.run() }
def reportFailure(t: Throwable) { t.printStackTrace() }
}
def withScheduler(start: Long = 0L, _startTick: Int = 0, config: Config = ConfigFactory.empty)(thunk: (Scheduler with Closeable, Driver) ⇒ Unit): Unit = {
import akka.actor.{ LightArrayRevolverScheduler ⇒ LARS }
- val lbq = new AtomicReference[LinkedBlockingQueue[Long]](new LinkedBlockingQueue[Long])
- val prb = TestProbe()
- val tf = system.asInstanceOf[ActorSystemImpl].threadFactory
- val sched =
- new { @volatile var time = start } with LARS(config.withFallback(system.settings.config), log, tf) {
+ val lbq: java.util.concurrent.atomic.AtomicReference[java.util.concurrent.LinkedBlockingQueue[Long]] = new AtomicReference[LinkedBlockingQueue[Long]](new LinkedBlockingQueue[Long])
+ val prb: akka.testkit.TestProbe = TestProbe()
+ val tf: akka.dispatch.MonitorableThreadFactory = system.asInstanceOf[ActorSystemImpl].threadFactory
+ val sched: akka.actor.LightArrayRevolverScheduler { def time: Long; def time_=(x$1: Long): Unit } =
+ new { @volatile var time: Long = start } with LARS(config.withFallback(system.settings.config), log, tf) {
override protected def clock(): Long = {
// println(s"clock=$time")
time
@@ -570,15 +570,15 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
override protected def startTick: Int = _startTick
}
- val driver = new Driver {
- def wakeUp(d: FiniteDuration) = lbq.get match {
+ val driver: LightArrayRevolverSchedulerSpec.this.Driver = new Driver {
+ def wakeUp(d: FiniteDuration): Unit = lbq.get match {
case q: LinkedBlockingQueue[Long] ⇒ q.offer(d.toNanos)
case _ ⇒
}
def expectWait(): FiniteDuration = probe.expectMsgType[Long].nanos
- def probe = prb
- def step = sched.TickDuration
- def close() = lbq.getAndSet(null) match {
+ def probe: akka.testkit.TestProbe = prb
+ def step: scala.concurrent.duration.FiniteDuration = sched.TickDuration
+ def close(): Unit = lbq.getAndSet(null) match {
case q: LinkedBlockingQueue[Long] ⇒ q.offer(0L)
case _ ⇒
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala b/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala
index 7edb248..e8bd029 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala
@@ -9,7 +9,7 @@ package akka.actor
*/
class Supervisor(override val supervisorStrategy: SupervisorStrategy) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x: Props ⇒ sender() ! context.actorOf(x)
}
// need to override the default of stopping all children upon restart, tests rely on keeping them around
diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala
index 7245676..9c8df6d 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala
@@ -37,19 +37,19 @@ object SupervisorHierarchySpec {
*/
class CountDownActor(countDown: CountDownLatch, override val supervisorStrategy: SupervisorStrategy) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case p: Props ⇒ sender() ! context.actorOf(p)
}
// test relies on keeping children around during restart
override def preRestart(cause: Throwable, msg: Option[Any]) {}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
countDown.countDown()
}
}
class Resumer extends Actor {
- override def supervisorStrategy = OneForOneStrategy() { case _ ⇒ SupervisorStrategy.Resume }
- def receive = {
+ override def supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() { case _ ⇒ SupervisorStrategy.Resume }
+ def receive: PartialFunction[Any, Unit] = {
case "spawn" ⇒ sender() ! context.actorOf(Props[Resumer])
case "fail" ⇒ throw new Exception("expected")
case "ping" ⇒ sender() ! "pong"
@@ -65,11 +65,11 @@ object SupervisorHierarchySpec {
final case class ErrorLog(msg: String, log: Vector[Event])
final case class Failure(directive: Directive, stop: Boolean, depth: Int, var failPre: Int, var failPost: Int, val failConstr: Int, stopKids: Int)
extends RuntimeException("Failure") with NoStackTrace {
- override def toString = productPrefix + productIterator.mkString("(", ",", ")")
+ override def toString: String = productPrefix + productIterator.mkString("(", ",", ")")
}
final case class Dump(level: Int)
- val config = ConfigFactory.parseString("""
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""
hierarchy {
type = "akka.actor.SupervisorHierarchySpec$MyDispatcherConfigurator"
}
@@ -117,16 +117,16 @@ object SupervisorHierarchySpec {
* is undesirable).
*/
final case class HierarchyState(log: Vector[Event], kids: Map[ActorPath, Int], failConstr: Failure)
- val stateCache = new ConcurrentHashMap[ActorPath, HierarchyState]()
+ val stateCache: java.util.concurrent.ConcurrentHashMap[akka.actor.ActorPath, akka.actor.SupervisorHierarchySpec.HierarchyState] = new ConcurrentHashMap[ActorPath, HierarchyState]()
@volatile var ignoreFailConstr = false
class Hierarchy(size: Int, breadth: Int, listener: ActorRef, myLevel: Int, random: Random) extends Actor {
- var log = Vector.empty[Event]
+ var log: scala.collection.immutable.Vector[akka.actor.SupervisorHierarchySpec.Event] = Vector.empty[Event]
stateCache.get(self.path) match {
case hs @ HierarchyState(l: Vector[Event], _, f: Failure) if f.failConstr > 0 && !ignoreFailConstr ⇒
- val log = l :+ Event("Failed in constructor", identityHashCode(this))
+ val log: scala.collection.immutable.Vector[akka.actor.SupervisorHierarchySpec.Event] = l :+ Event("Failed in constructor", identityHashCode(this))
stateCache.put(self.path, hs.copy(log = log, failConstr = f.copy(failConstr = f.failConstr - 1)))
throw f
case _ ⇒
@@ -148,21 +148,21 @@ object SupervisorHierarchySpec {
case _ ⇒
}
- def suspendCount = context.asInstanceOf[ActorCell].mailbox.suspendCount
+ def suspendCount: Int = context.asInstanceOf[ActorCell].mailbox.suspendCount
override def preStart {
log :+= Event("started", identityHashCode(this))
listener ! Ready(self)
- val s = size - 1 // subtract myself
+ val s: Int = size - 1 // subtract myself
val kidInfo: Map[ActorPath, Int] =
if (s > 0) {
- val kids = random.nextInt(Math.min(breadth, s)) + 1
- val sizes = s / kids
+ val kids: Int = random.nextInt(Math.min(breadth, s)) + 1
+ val sizes: Int = s / kids
var rest = s % kids
- val propsTemplate = Props.empty.withDispatcher("hierarchy")
+ val propsTemplate: akka.actor.Props = Props.empty.withDispatcher("hierarchy")
(1 to kids).map { (id) ⇒
- val kidSize = if (rest > 0) { rest -= 1; sizes + 1 } else sizes
- val props = Props(new Hierarchy(kidSize, breadth, listener, myLevel + 1, random)).withDeploy(propsTemplate.deploy)
+ val kidSize: Int = if (rest > 0) { rest -= 1; sizes + 1 } else sizes
+ val props: akka.actor.Props = Props(new Hierarchy(kidSize, breadth, listener, myLevel + 1, random)).withDeploy(propsTemplate.deploy)
(context.watch(context.actorOf(props, id.toString)).path, kidSize)
}(collection.breakOut)
} else Map()
@@ -198,7 +198,7 @@ object SupervisorHierarchySpec {
case x @ ActorInitializationException(_, _, f: Failure) ⇒ (f, x)
case x ⇒ (x, x)
}
- override val supervisorStrategy = OneForOneStrategy()(unwrap andThen {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy()(unwrap andThen {
case (_: Failure, _) if pongsToGo > 0 ⇒
log :+= Event("pongOfDeath resuming " + sender(), identityHashCode(this))
Resume
@@ -208,7 +208,7 @@ object SupervisorHierarchySpec {
log :+= Event("escalating " + f + " from " + sender(), identityHashCode(this))
throw f.copy(depth = f.depth - 1)
}
- val prefix = orig match {
+ val prefix: String = orig match {
case f: Failure ⇒ "applying "
case _ ⇒ "re-applying "
}
@@ -222,15 +222,15 @@ object SupervisorHierarchySpec {
})
override def postRestart(cause: Throwable) {
- val state = stateCache.get(self.path)
+ val state: akka.actor.SupervisorHierarchySpec.HierarchyState = stateCache.get(self.path)
log = state.log
log :+= Event("restarted " + suspendCount + " " + cause, identityHashCode(this))
state.kids foreach {
case (childPath, kidSize) ⇒
- val name = childPath.name
+ val name: String = childPath.name
if (context.child(name).isEmpty) {
listener ! Died(childPath)
- val props = Props(new Hierarchy(kidSize, breadth, listener, myLevel + 1, random)).withDispatcher("hierarchy")
+ val props: akka.actor.Props = Props(new Hierarchy(kidSize, breadth, listener, myLevel + 1, random)).withDispatcher("hierarchy")
context.watch(context.actorOf(props, name))
}
}
@@ -247,7 +247,7 @@ object SupervisorHierarchySpec {
override def postStop {
if (failed || suspended) {
listener ! ErrorLog("not resumed (" + failed + ", " + suspended + ")", log)
- val state = stateCache.get(self)
+ val state: akka.actor.SupervisorHierarchySpec.HierarchyState = stateCache.get(self)
if (state ne null) stateCache.put(self.path, state.copy(log = log))
} else {
stateCache.put(self.path, HierarchyState(log, Map(), null))
@@ -273,7 +273,7 @@ object SupervisorHierarchySpec {
var pongsToGo = 0
- def receive = new Receive {
+ def receive: Hierarchy.this.Receive = new Receive {
val handler: Receive = {
case f: Failure ⇒
setFlags(f.directive)
@@ -287,12 +287,12 @@ object SupervisorHierarchySpec {
* It might be that we acted upon this death already in postRestart
* (if the unwatch() came too late), so just ignore in this case.
*/
- val name = ref.path.name
+ val name: String = ref.path.name
if (pongsToGo == 0) {
if (!context.child(name).exists(_ != ref)) {
listener ! Died(ref.path)
- val kids = stateCache.get(self.path).kids(ref.path)
- val props = Props(new Hierarchy(kids, breadth, listener, myLevel + 1, random)).withDispatcher("hierarchy")
+ val kids: Int = stateCache.get(self.path).kids(ref.path)
+ val props: akka.actor.Props = Props(new Hierarchy(kids, breadth, listener, myLevel + 1, random)).withDispatcher("hierarchy")
context.watch(context.actorOf(props, name))
}
// Otherwise it is a Terminated from an old child. Ignore.
@@ -318,8 +318,8 @@ object SupervisorHierarchySpec {
context.parent ! PongOfDeath
}
}
- override def isDefinedAt(msg: Any) = handler.isDefinedAt(msg)
- override def apply(msg: Any) = { if (check(msg)) handler(msg) }
+ override def isDefinedAt(msg: Any): Boolean = handler.isDefinedAt(msg)
+ override def apply(msg: Any): Unit = { if (check(msg)) handler(msg) }
}
}
@@ -401,33 +401,33 @@ object SupervisorHierarchySpec {
class StressTest(testActor: ActorRef, size: Int, breadth: Int) extends Actor with LoggingFSM[State, Int] {
import context.system
- val randomSeed = System.nanoTime()
- val random = new Random(randomSeed)
+ val randomSeed: Long = System.nanoTime()
+ val random: scala.util.Random = new Random(randomSeed)
// don’t escalate from this one!
- override val supervisorStrategy = OneForOneStrategy() {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case f: Failure ⇒ f.directive
case OriginalRestartException(f: Failure) ⇒ f.directive
case ActorInitializationException(_, _, f: Failure) ⇒ f.directive
case _ ⇒ Stop
}
- var children = Vector.empty[ActorRef]
- var activeChildren = Vector.empty[ActorRef]
- var idleChildren = Vector.empty[ActorRef]
- var pingChildren = Set.empty[ActorRef]
+ var children: scala.collection.immutable.Vector[akka.actor.ActorRef] = Vector.empty[ActorRef]
+ var activeChildren: scala.collection.immutable.Vector[akka.actor.ActorRef] = Vector.empty[ActorRef]
+ var idleChildren: scala.collection.immutable.Vector[akka.actor.ActorRef] = Vector.empty[ActorRef]
+ var pingChildren: scala.collection.immutable.Set[akka.actor.ActorRef] = Set.empty[ActorRef]
- val nextJob = Iterator.continually(random.nextFloat match {
+ val nextJob: Iterator[Product with Serializable with akka.actor.SupervisorHierarchySpec.Action] = Iterator.continually(random.nextFloat match {
case x if x >= 0.5 ⇒
// ping one child
- val pick = ((x - 0.5) * 2 * idleChildren.size).toInt
- val ref = idleChildren(pick)
+ val pick: Int = ((x - 0.5) * 2 * idleChildren.size).toInt
+ val ref: akka.actor.ActorRef = idleChildren(pick)
idleChildren = idleChildren.take(pick) ++ idleChildren.drop(pick + 1)
pingChildren += ref
Ping(ref)
case x ⇒
// fail one child
- val pick = ((if (x >= 0.25) x - 0.25 else x) * 4 * activeChildren.size).toInt
+ val pick: Int = ((if (x >= 0.25) x - 0.25 else x) * 4 * activeChildren.size).toInt
Fail(activeChildren(pick), if (x > 0.25) Restart else Resume)
})
@@ -479,7 +479,7 @@ object SupervisorHierarchySpec {
setTimer("phase", StateTimeout, 90.seconds.dilated, false)
}
- val workSchedule = 50.millis
+ val workSchedule: scala.concurrent.duration.FiniteDuration = 50.millis
private def random012: Int = random.nextFloat match {
case x if x > 0.1 ⇒ 0
@@ -487,9 +487,9 @@ object SupervisorHierarchySpec {
case _ ⇒ 2
}
private def bury(path: ActorPath): Unit = {
- val deadGuy = path.elements
- val deadGuySize = deadGuy.size
- val isChild = (other: ActorRef) ⇒ other.path.elements.take(deadGuySize) == deadGuy
+ val deadGuy: scala.collection.immutable.Iterable[String] = path.elements
+ val deadGuySize: Int = deadGuy.size
+ val isChild: akka.actor.ActorRef ⇒ Boolean = (other: ActorRef) ⇒ other.path.elements.take(deadGuySize) == deadGuy
activeChildren = activeChildren filterNot isChild
idleChildren = idleChildren filterNot isChild
pingChildren = pingChildren filterNot isChild
@@ -505,7 +505,7 @@ object SupervisorHierarchySpec {
nextJob.next match {
case Ping(ref) ⇒ ref ! "ping"
case Fail(ref, dir) ⇒
- val f = Failure(dir, stop = random012 > 0, depth = random012, failPre = random012, failPost = random012, failConstr = random012,
+ val f: akka.actor.SupervisorHierarchySpec.Failure = Failure(dir, stop = random012 > 0, depth = random012, failPre = random012, failPost = random012, failConstr = random012,
stopKids = random012 match {
case 0 ⇒ 0
case 1 ⇒ random.nextInt(breadth / 2)
@@ -575,7 +575,7 @@ object SupervisorHierarchySpec {
when(Stopping, stateTimeout = 5.seconds.dilated) {
case Event(PongOfDeath, _) ⇒ stay
case Event(Terminated(r), _) if r == hierarchy ⇒
- val undead = children filterNot (_.isTerminated)
+ val undead: scala.collection.immutable.Vector[akka.actor.ActorRef] = children filterNot (_.isTerminated)
if (undead.nonEmpty) {
log.info("undead:\n" + undead.mkString("\n"))
testActor ! "stressTestFailed (" + undead.size + " undead)"
@@ -588,7 +588,7 @@ object SupervisorHierarchySpec {
* failed. I’m leaving this code in so that manual inspection remains
* an option (by setting the above condition to “true”).
*/
- val weak = children map (new WeakReference(_))
+ val weak: scala.collection.immutable.Vector[java.lang.ref.WeakReference[akka.actor.ActorRef]] = children map (new WeakReference(_))
children = Vector.empty
pingChildren = Set.empty
idleChildren = Vector.empty
@@ -614,7 +614,7 @@ object SupervisorHierarchySpec {
when(GC, stateTimeout = 10 seconds) {
case Event(GCcheck(weak), _) ⇒
- val next = weak filter (_.get ne null)
+ val next: scala.collection.immutable.Vector[java.lang.ref.WeakReference[akka.actor.ActorRef]] = weak filter (_.get ne null)
if (next.nonEmpty) {
println(next.size + " left")
context.system.scheduler.scheduleOnce(workSchedule, self, GCcheck(next))(context.dispatcher)
@@ -629,7 +629,7 @@ object SupervisorHierarchySpec {
stop
}
- var errors = Vector.empty[(ActorRef, ErrorLog)]
+ var errors: scala.collection.immutable.Vector[(akka.actor.ActorRef, akka.actor.SupervisorHierarchySpec.ErrorLog)] = Vector.empty[(ActorRef, ErrorLog)]
when(Failed, stateTimeout = 5.seconds.dilated) {
case Event(e: ErrorLog, _) ⇒
@@ -679,7 +679,7 @@ object SupervisorHierarchySpec {
case (origin, ErrorLog("dump", _)) ⇒ getErrors(origin, 1)
case (origin, ErrorLog(msg, _)) if msg startsWith "not resumed" ⇒ getErrorsUp(origin)
}
- val merged = errors.sortBy(_._1.toString) flatMap {
+ val merged: scala.collection.immutable.Vector[(Long, akka.actor.ActorRef, Long, String)] = errors.sortBy(_._1.toString) flatMap {
case (ref, ErrorLog(msg, log)) ⇒
println("Error: " + ref + " " + msg)
log map (l ⇒ (l.time, ref, l.identity, l.msg.toString))
@@ -725,19 +725,19 @@ object SupervisorHierarchySpec {
class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) with DefaultTimeout with ImplicitSender {
import SupervisorHierarchySpec._
- override def expectedTestDuration = 2.minutes
+ override def expectedTestDuration: scala.concurrent.duration.FiniteDuration = 2.minutes
"A Supervisor Hierarchy" must {
"restart manager and workers in AllForOne" taggedAs LongRunningTest in {
- val countDown = new CountDownLatch(4)
+ val countDown: java.util.concurrent.CountDownLatch = new CountDownLatch(4)
- val boss = system.actorOf(Props(new Supervisor(OneForOneStrategy()(List(classOf[Exception])))))
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(OneForOneStrategy()(List(classOf[Exception])))))
- val managerProps = Props(new CountDownActor(countDown, AllForOneStrategy()(List())))
- val manager = Await.result((boss ? managerProps).mapTo[ActorRef], timeout.duration)
+ val managerProps: akka.actor.Props = Props(new CountDownActor(countDown, AllForOneStrategy()(List())))
+ val manager: akka.actor.ActorRef = Await.result((boss ? managerProps).mapTo[ActorRef], timeout.duration)
- val workerProps = Props(new CountDownActor(countDown, SupervisorStrategy.defaultStrategy))
+ val workerProps: akka.actor.Props = Props(new CountDownActor(countDown, SupervisorStrategy.defaultStrategy))
val workerOne, workerTwo, workerThree = Await.result((manager ? workerProps).mapTo[ActorRef], timeout.duration)
filterException[ActorKilledException] {
@@ -751,15 +751,15 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
}
"send notification to supervisor when permanent failure" taggedAs LongRunningTest in {
- val countDownMessages = new CountDownLatch(1)
- val countDownMax = new CountDownLatch(1)
- val boss = system.actorOf(Props(new Actor {
- override val supervisorStrategy =
+ val countDownMessages: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val countDownMax: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy =
OneForOneStrategy(maxNrOfRetries = 1, withinTimeRange = 5 seconds)(List(classOf[Throwable]))
- val crasher = context.watch(context.actorOf(Props(new CountDownActor(countDownMessages, SupervisorStrategy.defaultStrategy))))
+ val crasher: akka.actor.ActorRef = context.watch(context.actorOf(Props(new CountDownActor(countDownMessages, SupervisorStrategy.defaultStrategy))))
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "killCrasher" ⇒ crasher ! Kill
case Terminated(_) ⇒ countDownMax.countDown()
}
@@ -775,11 +775,11 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
}
"resume children after Resume" taggedAs LongRunningTest in {
- val boss = system.actorOf(Props[Resumer], "resumer")
+ val boss: akka.actor.ActorRef = system.actorOf(Props[Resumer], "resumer")
boss ! "spawn"
- val middle = expectMsgType[ActorRef]
+ val middle: akka.actor.ActorRef = expectMsgType[ActorRef]
middle ! "spawn"
- val worker = expectMsgType[ActorRef]
+ val worker: akka.actor.ActorRef = expectMsgType[ActorRef]
worker ! "ping"
expectMsg("pong")
EventFilter.warning("expected", occurrences = 1) intercept {
@@ -792,19 +792,19 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
}
"suspend children while failing" taggedAs LongRunningTest in {
- val latch = TestLatch()
- val slowResumer = system.actorOf(Props(new Actor {
- override def supervisorStrategy = OneForOneStrategy() { case _ ⇒ Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume }
- def receive = {
+ val latch: akka.testkit.TestLatch = TestLatch()
+ val slowResumer: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override def supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() { case _ ⇒ Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume }
+ def receive: PartialFunction[Any, Unit] = {
case "spawn" ⇒ sender() ! context.actorOf(Props[Resumer])
}
}), "slowResumer")
slowResumer ! "spawn"
- val boss = expectMsgType[ActorRef]
+ val boss: akka.actor.ActorRef = expectMsgType[ActorRef]
boss ! "spawn"
- val middle = expectMsgType[ActorRef]
+ val middle: akka.actor.ActorRef = expectMsgType[ActorRef]
middle ! "spawn"
- val worker = expectMsgType[ActorRef]
+ val worker: akka.actor.ActorRef = expectMsgType[ActorRef]
worker ! "ping"
expectMsg("pong")
EventFilter.warning("expected", occurrences = 1) intercept {
@@ -818,9 +818,9 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
}
"handle failure in creation when supervision startegy returns Resume and Restart" taggedAs LongRunningTest in {
- val createAttempt = new AtomicInteger(0)
- val preStartCalled = new AtomicInteger(0)
- val postRestartCalled = new AtomicInteger(0)
+ val createAttempt: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val preStartCalled: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val postRestartCalled: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
filterEvents(
EventFilter[Failure](),
@@ -828,33 +828,33 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
EventFilter[IllegalArgumentException]("OH NO!"),
EventFilter.error(start = "changing Recreate into Create"),
EventFilter.error(start = "changing Resume into Create")) {
- val failResumer = system.actorOf(Props(new Actor {
- override def supervisorStrategy = OneForOneStrategy() {
+ val failResumer: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override def supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case e: ActorInitializationException ⇒
if (createAttempt.get % 2 == 0) SupervisorStrategy.Resume else SupervisorStrategy.Restart
}
- val child = context.actorOf(Props(new Actor {
- val ca = createAttempt.incrementAndGet()
+ val child: akka.actor.ActorRef = context.actorOf(Props(new Actor {
+ val ca: Int = createAttempt.incrementAndGet()
if (ca <= 6 && ca % 3 == 0)
- context.actorOf(Props(new Actor { override def receive = { case _ ⇒ } }), "workingChild")
+ context.actorOf(Props(new Actor { override def receive: PartialFunction[Any, Unit] = { case _ ⇒ } }), "workingChild")
if (ca < 6) {
throw new IllegalArgumentException("OH NO!")
}
- override def preStart() = {
+ override def preStart(): Unit = {
preStartCalled.incrementAndGet()
}
- override def postRestart(reason: Throwable) = {
+ override def postRestart(reason: Throwable): Unit = {
postRestartCalled.incrementAndGet()
}
- override def receive = {
+ override def receive: PartialFunction[Any, Unit] = {
case m ⇒ sender() ! m
}
}), "failChild")
- override def receive = {
+ override def receive: PartialFunction[Any, Unit] = {
case m ⇒ child.forward(m)
}
}), "failResumer")
@@ -878,10 +878,10 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
EventFilter.error(start = "changing Recreate into Create"),
EventFilter.warning(start = "received dead ")))
- val fsm = system.actorOf(Props(new StressTest(testActor, size = 500, breadth = 6)), "stressTest")
+ val fsm: akka.actor.ActorRef = system.actorOf(Props(new StressTest(testActor, size = 500, breadth = 6)), "stressTest")
fsm ! FSM.SubscribeTransitionCallBack(system.actorOf(Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case s: FSM.CurrentState[_] ⇒ log.info("{}", s)
case t: FSM.Transition[_] ⇒ log.info("{}", t)
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala
index f41b9f3..4220617 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala
@@ -32,14 +32,14 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
"restart a crashing actor and its dispatcher for any dispatcher" in {
filterEvents(EventFilter[Exception]("Kill")) {
- val countDownLatch = new CountDownLatch(4)
+ val countDownLatch: java.util.concurrent.CountDownLatch = new CountDownLatch(4)
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5 seconds)(List(classOf[Exception])))))
- val workerProps = Props(new Actor {
+ val workerProps: akka.actor.Props = Props(new Actor {
override def postRestart(cause: Throwable) { countDownLatch.countDown() }
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "status" ⇒ this.sender() ! "OK"
case _ ⇒ this.context.stop(self)
}
@@ -47,9 +47,9 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
val actor1, actor2 = Await.result((supervisor ? workerProps.withDispatcher("pinned-dispatcher")).mapTo[ActorRef], timeout.duration)
- val actor3 = Await.result((supervisor ? workerProps.withDispatcher("test-dispatcher")).mapTo[ActorRef], timeout.duration)
+ val actor3: akka.actor.ActorRef = Await.result((supervisor ? workerProps.withDispatcher("test-dispatcher")).mapTo[ActorRef], timeout.duration)
- val actor4 = Await.result((supervisor ? workerProps.withDispatcher("pinned-dispatcher")).mapTo[ActorRef], timeout.duration)
+ val actor4: akka.actor.ActorRef = Await.result((supervisor ? workerProps.withDispatcher("pinned-dispatcher")).mapTo[ActorRef], timeout.duration)
actor1 ! Kill
actor2 ! Kill
@@ -67,9 +67,9 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
}
"be able to create named children in its constructor" in {
- val a = system.actorOf(Props(new Actor {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.actorOf(Props.empty, "bob")
- def receive = { case x: Exception ⇒ throw x }
+ def receive: PartialFunction[Any, Unit] = { case x: Exception ⇒ throw x }
override def preStart(): Unit = testActor ! "preStart"
}))
val m = "weird message"
@@ -82,13 +82,13 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
}
"be able to recreate child when old child is Terminated" in {
- val parent = system.actorOf(Props(new Actor {
- val kid = context.watch(context.actorOf(Props.empty, "foo"))
- def receive = {
+ val parent: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ val kid: akka.actor.ActorRef = context.watch(context.actorOf(Props.empty, "foo"))
+ def receive: PartialFunction[Any, Unit] = {
case Terminated(`kid`) ⇒
try {
- val newKid = context.actorOf(Props.empty, "foo")
- val result =
+ val newKid: akka.actor.ActorRef = context.actorOf(Props.empty, "foo")
+ val result: String =
if (newKid eq kid) "Failure: context.actorOf returned the same instance!"
else if (!kid.isTerminated) "Kid is zombie"
else if (newKid.isTerminated) "newKid was stillborn"
@@ -106,11 +106,11 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
}
"not be able to recreate child when old child is alive" in {
- val parent = system.actorOf(Props(new Actor {
- def receive = {
+ val parent: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "engage" ⇒
try {
- val kid = context.actorOf(Props.empty, "foo")
+ val kid: akka.actor.ActorRef = context.actorOf(Props.empty, "foo")
context.stop(kid)
context.actorOf(Props.empty, "foo")
testActor ! "red"
@@ -124,15 +124,15 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
}
"be able to create a similar kid in the fault handling strategy" in {
- val parent = system.actorOf(Props(new Actor {
- override val supervisorStrategy = new OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider) {
+ val parent: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = new OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider) {
override def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = {
- val newKid = context.actorOf(Props.empty, child.path.name)
+ val newKid: akka.actor.ActorRef = context.actorOf(Props.empty, child.path.name)
testActor ! { if ((newKid ne child) && newKid.path == child.path) "green" else "red" }
}
}
- def receive = { case "engage" ⇒ context.stop(context.actorOf(Props.empty, "Robert")) }
+ def receive: PartialFunction[Any, Unit] = { case "engage" ⇒ context.stop(context.actorOf(Props.empty, "Robert")) }
}))
parent ! "engage"
expectMsg("green")
@@ -142,18 +142,18 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
}
"have access to the failing child’s reference in supervisorStrategy" in {
- val parent = system.actorOf(Props(new Actor {
- override val supervisorStrategy = OneForOneStrategy() {
+ val parent: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case _: Exception ⇒ testActor ! sender(); SupervisorStrategy.Stop
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "doit" ⇒ context.actorOf(Props.empty, "child") ! Kill
}
}))
EventFilter[ActorKilledException](occurrences = 1) intercept {
parent ! "doit"
}
- val p = expectMsgType[ActorRef].path
+ val p: akka.actor.ActorPath = expectMsgType[ActorRef].path
p.parent should ===(parent.path)
p.name should ===("child")
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala
index 8aa4bac..669a073 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala
@@ -21,7 +21,7 @@ import akka.ConfigurationException
import akka.routing.RoundRobinPool
object SupervisorSpec {
- val Timeout = 5.seconds
+ val Timeout: scala.concurrent.duration.FiniteDuration = 5.seconds
case object DieReply
@@ -38,7 +38,7 @@ object SupervisorSpec {
// =====================================================
class PingPongActor(sendTo: ActorRef) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒
sendTo ! PingMessage
if (sender() != sendTo)
@@ -46,7 +46,7 @@ object SupervisorSpec {
case Die ⇒
throw new RuntimeException(ExceptionMessage)
case DieReply ⇒
- val e = new RuntimeException(ExceptionMessage)
+ val e: RuntimeException = new RuntimeException(ExceptionMessage)
sender() ! Status.Failure(e)
throw e
}
@@ -57,13 +57,13 @@ object SupervisorSpec {
}
class Master(sendTo: ActorRef) extends Actor {
- val temp = context.watch(context.actorOf(Props(new PingPongActor(sendTo))))
+ val temp: akka.actor.ActorRef = context.watch(context.actorOf(Props(new PingPongActor(sendTo))))
var s: ActorRef = _
- override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 0)(List(classOf[Exception]))
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy(maxNrOfRetries = 0)(List(classOf[Exception]))
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Die ⇒ temp forward Die
case Terminated(`temp`) ⇒ sendTo ! "terminated"
case Status.Failure(_) ⇒ /*Ignore*/
@@ -71,29 +71,29 @@ object SupervisorSpec {
}
class Creator(target: ActorRef) extends Actor {
- override val supervisorStrategy = OneForOneStrategy() {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case ex ⇒
target ! ((self, sender(), ex))
SupervisorStrategy.Stop
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case p: Props ⇒ sender() ! context.actorOf(p)
}
}
- def creator(target: ActorRef, fail: Boolean = false) = {
- val p = Props(new Creator(target))
+ def creator(target: ActorRef, fail: Boolean = false): akka.actor.Props = {
+ val p: akka.actor.Props = Props(new Creator(target))
if (fail) p.withMailbox("error-mailbox") else p
}
- val failure = new AssertionError("deliberate test failure")
+ val failure: AssertionError = new AssertionError("deliberate test failure")
class Mailbox(settings: ActorSystem.Settings, config: Config) extends MailboxType {
override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue =
throw failure
}
- val config = ConfigFactory.parseString("""
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.actor.serialize-messages = off
error-mailbox {
mailbox-type = "akka.actor.SupervisorSpec$Mailbox"
@@ -105,7 +105,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
import SupervisorSpec._
- val DilatedTimeout = Timeout.dilated
+ val DilatedTimeout: scala.concurrent.duration.FiniteDuration = Timeout.dilated
// =====================================================
// Creating actors and supervisors
@@ -114,30 +114,30 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
private def child(supervisor: ActorRef, props: Props): ActorRef = Await.result((supervisor ? props).mapTo[ActorRef], timeout.duration)
def temporaryActorAllForOne = {
- val supervisor = system.actorOf(Props(new Supervisor(AllForOneStrategy(maxNrOfRetries = 0)(List(classOf[Exception])))))
- val temporaryActor = child(supervisor, Props(new PingPongActor(testActor)))
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(AllForOneStrategy(maxNrOfRetries = 0)(List(classOf[Exception])))))
+ val temporaryActor: akka.actor.ActorRef = child(supervisor, Props(new PingPongActor(testActor)))
(temporaryActor, supervisor)
}
def singleActorAllForOne = {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
AllForOneStrategy(maxNrOfRetries = 3, withinTimeRange = DilatedTimeout)(List(classOf[Exception])))))
- val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
+ val pingpong: akka.actor.ActorRef = child(supervisor, Props(new PingPongActor(testActor)))
(pingpong, supervisor)
}
def singleActorOneForOne = {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = DilatedTimeout)(List(classOf[Exception])))))
- val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
+ val pingpong: akka.actor.ActorRef = child(supervisor, Props(new PingPongActor(testActor)))
(pingpong, supervisor)
}
def multipleActorsAllForOne = {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
AllForOneStrategy(maxNrOfRetries = 3, withinTimeRange = DilatedTimeout)(List(classOf[Exception])))))
val pingpong1, pingpong2, pingpong3 = child(supervisor, Props(new PingPongActor(testActor)))
@@ -145,7 +145,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
def multipleActorsOneForOne = {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = DilatedTimeout)(List(classOf[Exception])))))
val pingpong1, pingpong2, pingpong3 = child(supervisor, Props(new PingPongActor(testActor)))
@@ -153,11 +153,11 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
def nestedSupervisorsAllForOne = {
- val topSupervisor = system.actorOf(Props(new Supervisor(
+ val topSupervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
AllForOneStrategy(maxNrOfRetries = 3, withinTimeRange = DilatedTimeout)(List(classOf[Exception])))))
- val pingpong1 = child(topSupervisor, Props(new PingPongActor(testActor)))
+ val pingpong1: akka.actor.ActorRef = child(topSupervisor, Props(new PingPongActor(testActor)))
- val middleSupervisor = child(topSupervisor, Props(new Supervisor(
+ val middleSupervisor: akka.actor.ActorRef = child(topSupervisor, Props(new Supervisor(
AllForOneStrategy(maxNrOfRetries = 3, withinTimeRange = DilatedTimeout)(Nil))))
val pingpong2, pingpong3 = child(middleSupervisor, Props(new PingPongActor(testActor)))
@@ -168,23 +168,23 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
system.eventStream.publish(Mute(EventFilter[RuntimeException](ExceptionMessage)))
}
- override def beforeEach() = {
+ override def beforeEach(): Unit = {
}
- def ping(pingPongActor: ActorRef) = {
+ def ping(pingPongActor: ActorRef): String = {
Await.result(pingPongActor.?(Ping)(DilatedTimeout), DilatedTimeout) should ===(PongMessage)
expectMsg(Timeout, PingMessage)
}
- def kill(pingPongActor: ActorRef) = {
- val result = (pingPongActor.?(DieReply)(DilatedTimeout))
+ def kill(pingPongActor: ActorRef): RuntimeException = {
+ val result: scala.concurrent.Future[Any] = (pingPongActor.?(DieReply)(DilatedTimeout))
expectMsg(Timeout, ExceptionMessage) //this is sent from PingPongActor's postRestart()
intercept[RuntimeException] { Await.result(result, DilatedTimeout) }
}
- def killExpectNoRestart(pingPongActor: ActorRef) = {
- val result = (pingPongActor.?(DieReply)(DilatedTimeout))
+ def killExpectNoRestart(pingPongActor: ActorRef): RuntimeException = {
+ val result: scala.concurrent.Future[Any] = (pingPongActor.?(DieReply)(DilatedTimeout))
expectNoMsg(500 milliseconds)
intercept[RuntimeException] { Await.result(result, DilatedTimeout) }
}
@@ -192,7 +192,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
"A supervisor" must {
"not restart child more times than permitted" in {
- val master = system.actorOf(Props(new Master(testActor)))
+ val master: akka.actor.ActorRef = system.actorOf(Props(new Master(testActor)))
master ! Die
expectMsg(3 seconds, "terminated")
@@ -201,7 +201,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
"restart properly when same instance is returned" in {
val restarts = 3 //max number of restarts
- lazy val childInstance = new Actor {
+ lazy val childInstance: akka.actor.Actor { def preRestarts: Int; def preRestarts_=(x$1: Int): Unit; def postRestarts: Int; def postRestarts_=(x$1: Int): Unit; def preStarts: Int; def preStarts_=(x$1: Int): Unit; def postStops: Int; def postStops_=(x$1: Int): Unit } = new Actor {
var preRestarts = 0
var postRestarts = 0
var preStarts = 0
@@ -210,15 +210,15 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
override def postRestart(reason: Throwable) { postRestarts += 1; testActor ! ("postRestart" + postRestarts) }
override def preStart() { preStarts += 1; testActor ! ("preStart" + preStarts) }
override def postStop() { postStops += 1; testActor ! ("postStop" + postStops) }
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "crash" ⇒ { testActor ! "crashed"; throw new RuntimeException("Expected") }
case "ping" ⇒ sender() ! "pong"
}
}
- val master = system.actorOf(Props(new Actor {
- override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = restarts)(List(classOf[Exception]))
- val child = context.actorOf(Props(childInstance))
- def receive = {
+ val master: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy(maxNrOfRetries = restarts)(List(classOf[Exception]))
+ val child: akka.actor.ActorRef = context.actorOf(Props(childInstance))
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ child forward msg
}
}))
@@ -376,28 +376,28 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
"attempt restart when exception during restart" in {
- val inits = new AtomicInteger(0)
- val supervisor = system.actorOf(Props(new Supervisor(
+ val inits: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 10 seconds)(classOf[Exception] :: Nil))))
- val dyingProps = Props(new Actor {
- val init = inits.getAndIncrement()
+ val dyingProps: akka.actor.Props = Props(new Actor {
+ val init: Int = inits.getAndIncrement()
if (init % 3 == 1) throw new IllegalStateException("Don't wanna!")
override def preRestart(cause: Throwable, msg: Option[Any]) {
if (init % 3 == 0) throw new IllegalStateException("Don't wanna!")
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒ sender() ! PongMessage
case DieReply ⇒
- val e = new RuntimeException("Expected")
+ val e: RuntimeException = new RuntimeException("Expected")
sender() ! Status.Failure(e)
throw e
}
})
supervisor ! dyingProps
- val dyingActor = expectMsgType[ActorRef]
+ val dyingActor: akka.actor.ActorRef = expectMsgType[ActorRef]
filterEvents(
EventFilter[RuntimeException]("Expected", occurrences = 1),
@@ -417,14 +417,14 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
"not lose system messages when a NonFatal exception occurs when processing a system message" in {
- val parent = system.actorOf(Props(new Actor {
- override val supervisorStrategy = OneForOneStrategy()({
+ val parent: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy()({
case e: IllegalStateException if e.getMessage == "OHNOES" ⇒ throw e
case _ ⇒ SupervisorStrategy.Restart
})
- val child = context.watch(context.actorOf(Props(new Actor {
+ val child: akka.actor.ActorRef = context.watch(context.actorOf(Props(new Actor {
override def postRestart(reason: Throwable): Unit = testActor ! "child restarted"
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case l: TestLatch ⇒ { Await.ready(l, 5 seconds); throw new IllegalStateException("OHNOES") }
case "test" ⇒ sender() ! "child green"
}
@@ -438,7 +438,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
postStop()
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Terminated(a) if a.path == child.path ⇒ testActor ! "child terminated"
case l: TestLatch ⇒ child ! l
case "test" ⇒ sender() ! "green"
@@ -447,7 +447,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
}))
- val latch = TestLatch()
+ val latch: akka.testkit.TestLatch = TestLatch()
parent ! latch
parent ! "testchildAndAck"
expectMsg("ack")
@@ -467,15 +467,15 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
"log pre-creation check failures" when {
"creating a top-level actor" in EventFilter[ActorInitializationException](occurrences = 1).intercept {
- val ref = system.actorOf(creator(testActor, fail = true))
+ val ref: akka.actor.ActorRef = system.actorOf(creator(testActor, fail = true))
watch(ref)
expectTerminated(ref)
}
"creating a normal child actor" in EventFilter[ConfigurationException](occurrences = 1).intercept {
- val top = system.actorOf(creator(testActor))
+ val top: akka.actor.ActorRef = system.actorOf(creator(testActor))
top ! creator(testActor)
- val middle = expectMsgType[ActorRef]
+ val middle: akka.actor.ActorRef = expectMsgType[ActorRef]
middle ! creator(testActor, fail = true)
expectMsgPF(hint = "ConfigurationException") {
case (top, middle, ex: ConfigurationException) ⇒
@@ -484,15 +484,15 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
"creating a top-level router" in EventFilter[ActorInitializationException](occurrences = 1).intercept {
- val ref = system.actorOf(creator(testActor, fail = true).withRouter(RoundRobinPool(1)))
+ val ref: akka.actor.ActorRef = system.actorOf(creator(testActor, fail = true).withRouter(RoundRobinPool(1)))
watch(ref)
expectTerminated(ref)
}
"creating a router" in EventFilter[ConfigurationException](occurrences = 1).intercept {
- val top = system.actorOf(creator(testActor))
+ val top: akka.actor.ActorRef = system.actorOf(creator(testActor))
top ! creator(testActor)
- val middle = expectMsgType[ActorRef]
+ val middle: akka.actor.ActorRef = expectMsgType[ActorRef]
middle ! creator(testActor, fail = true).withRouter(RoundRobinPool(1))
expectMsgPF(hint = "ConfigurationException") {
case (top, middle, ex: ConfigurationException) ⇒
@@ -504,10 +504,10 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
"restarts a child infinitely if maxNrOfRetries = -1 and withinTimeRange = Duration.Inf" in {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = -1, withinTimeRange = Duration.Inf)(classOf[Exception] :: Nil))))
- val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
+ val pingpong: akka.actor.ActorRef = child(supervisor, Props(new PingPongActor(testActor)))
kill(pingpong)
kill(pingpong)
@@ -520,10 +520,10 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
"treats maxNrOfRetries = -1 as maxNrOfRetries = 1 if withinTimeRange is non-infinite Duration" in {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = -1, withinTimeRange = 10 seconds)(classOf[Exception] :: Nil))))
- val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
+ val pingpong: akka.actor.ActorRef = child(supervisor, Props(new PingPongActor(testActor)))
ping(pingpong)
kill(pingpong)
@@ -532,10 +532,10 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter
}
"treats withinTimeRange = Duration.Inf as a single infinite restart window" in {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = Duration.Inf)(classOf[Exception] :: Nil))))
- val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
+ val pingpong: akka.actor.ActorRef = child(supervisor, Props(new PingPongActor(testActor)))
//impossible to confirm if the restart window is infinite, so making sure maxNrOfRetries is respected correctly
kill(pingpong)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala
index 3dd9489..4a989ec 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala
@@ -17,16 +17,16 @@ class SupervisorTreeSpec extends AkkaSpec("akka.actor.serialize-messages = off")
"be able to kill the middle actor and see itself and its child restarted" in {
EventFilter[ActorKilledException](occurrences = 1) intercept {
within(5 seconds) {
- val p = Props(new Actor {
- override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 1 second)(List(classOf[Exception]))
- def receive = {
+ val p: akka.actor.Props = Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 1 second)(List(classOf[Exception]))
+ def receive: PartialFunction[Any, Unit] = {
case p: Props ⇒ sender() ! context.actorOf(p)
}
override def preRestart(cause: Throwable, msg: Option[Any]) { testActor ! self.path }
})
- val headActor = system.actorOf(p)
- val middleActor = Await.result((headActor ? p).mapTo[ActorRef], timeout.duration)
- val lastActor = Await.result((middleActor ? p).mapTo[ActorRef], timeout.duration)
+ val headActor: akka.actor.ActorRef = system.actorOf(p)
+ val middleActor: akka.actor.ActorRef = Await.result((headActor ? p).mapTo[ActorRef], timeout.duration)
+ val lastActor: akka.actor.ActorRef = Await.result((middleActor ? p).mapTo[ActorRef], timeout.duration)
middleActor ! Kill
expectMsg(middleActor.path)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala b/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala
index 6982fd9..05f373c 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala
@@ -25,9 +25,9 @@ class Ticket669Spec extends AkkaSpec with BeforeAndAfterAll with ImplicitSender
"A supervised actor with lifecycle PERMANENT" should {
"be able to reply on failure during preRestart" in {
filterEvents(EventFilter[Exception]("test", occurrences = 1)) {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
AllForOneStrategy(5, 10 seconds)(List(classOf[Exception])))))
- val supervised = Await.result((supervisor ? Props[Supervised]).mapTo[ActorRef], timeout.duration)
+ val supervised: akka.actor.ActorRef = Await.result((supervisor ? Props[Supervised]).mapTo[ActorRef], timeout.duration)
supervised.!("test")(testActor)
expectMsg("failure1")
@@ -37,9 +37,9 @@ class Ticket669Spec extends AkkaSpec with BeforeAndAfterAll with ImplicitSender
"be able to reply on failure during postStop" in {
filterEvents(EventFilter[Exception]("test", occurrences = 1)) {
- val supervisor = system.actorOf(Props(new Supervisor(
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(
AllForOneStrategy(maxNrOfRetries = 0)(List(classOf[Exception])))))
- val supervised = Await.result((supervisor ? Props[Supervised]).mapTo[ActorRef], timeout.duration)
+ val supervised: akka.actor.ActorRef = Await.result((supervisor ? Props[Supervised]).mapTo[ActorRef], timeout.duration)
supervised.!("test")(testActor)
expectMsg("failure2")
@@ -51,7 +51,7 @@ class Ticket669Spec extends AkkaSpec with BeforeAndAfterAll with ImplicitSender
object Ticket669Spec {
class Supervised extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ throw new Exception("test")
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala
index 42e95a7..4989672 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala
@@ -54,7 +54,7 @@ object TimerSpec {
timers.startPeriodicTimer("T", Tick(bumpCount), interval)
}
- override def receive = {
+ override def receive: PartialFunction[Any, Unit] = {
case Tick(n) ⇒
monitor ! Tock(n)
case Bump ⇒
@@ -101,7 +101,7 @@ object TimerSpec {
}
{
- val i = initial()
+ val i: Int = initial()
startWith(TheState, i)
setTimer("T", Tick(i), interval, repeat)
}
@@ -147,8 +147,8 @@ class FsmTimerSpec extends AbstractTimerSpec {
abstract class AbstractTimerSpec extends AkkaSpec {
import TimerSpec._
- val interval = 1.second
- val dilatedInterval = interval.dilated
+ val interval: scala.concurrent.duration.FiniteDuration = 1.second
+ val dilatedInterval: scala.concurrent.duration.FiniteDuration = interval.dilated
def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int = () ⇒ 1): Props
@@ -156,8 +156,8 @@ abstract class AbstractTimerSpec extends AkkaSpec {
testName must {
"schedule non-repeated ticks" taggedAs TimingTest in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, 10.millis, repeat = false))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, 10.millis, repeat = false))
probe.expectMsg(Tock(1))
probe.expectNoMsg(100.millis)
@@ -167,8 +167,8 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"schedule repeated ticks" taggedAs TimingTest in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
probe.within((interval * 4) - 100.millis) {
probe.expectMsg(Tock(1))
probe.expectMsg(Tock(1))
@@ -180,10 +180,10 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"replace timer" taggedAs TimingTest in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
probe.expectMsg(Tock(1))
- val latch = new TestLatch(1)
+ val latch: akka.testkit.TestLatch = new TestLatch(1)
// next Tock(1) enqueued in mailboxed, but should be discarded because of new timer
ref ! SlowThenBump(latch)
probe.expectNoMsg(interval + 100.millis)
@@ -195,8 +195,8 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"cancel timer" taggedAs TimingTest in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
probe.expectMsg(Tock(1))
ref ! Cancel
probe.expectNoMsg(dilatedInterval + 100.millis)
@@ -206,8 +206,8 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"cancel timers when restarted" taggedAs TimingTest in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
ref ! Throw(new Exc)
probe.expectMsg(GotPreRestart(false))
@@ -216,13 +216,13 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"discard timers from old incarnation after restart, alt 1" taggedAs TimingTest in {
- val probe = TestProbe()
- val startCounter = new AtomicInteger(0)
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true,
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val startCounter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true,
initial = () ⇒ startCounter.incrementAndGet()))
probe.expectMsg(Tock(1))
- val latch = new TestLatch(1)
+ val latch: akka.testkit.TestLatch = new TestLatch(1)
// next Tock(1) is enqueued in mailbox, but should be discarded by new incarnation
ref ! SlowThenThrow(latch, new Exc)
probe.expectNoMsg(interval + 100.millis)
@@ -236,15 +236,15 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"discard timers from old incarnation after restart, alt 2" taggedAs TimingTest in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
probe.expectMsg(Tock(1))
// change state so that we see that the restart starts over again
ref ! Bump
probe.expectMsg(Tock(2))
- val latch = new TestLatch(1)
+ val latch: akka.testkit.TestLatch = new TestLatch(1)
// next Tock(2) is enqueued in mailbox, but should be discarded by new incarnation
ref ! SlowThenThrow(latch, new Exc)
probe.expectNoMsg(interval + 100.millis)
@@ -257,8 +257,8 @@ abstract class AbstractTimerSpec extends AkkaSpec {
}
"cancel timers when stopped" in {
- val probe = TestProbe()
- val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val ref: akka.actor.ActorRef = system.actorOf(target(probe.ref, dilatedInterval, repeat = true))
ref ! End
probe.expectMsg(GotPostStop(false))
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala
index e4dd665..b3be6c7 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala
@@ -38,13 +38,13 @@ object TypedActorSpec {
private[this] val current = new AtomicReference(items)
- def hasNext = items != Nil
+ def hasNext: Boolean = items != Nil
def next: T = {
@tailrec
def findNext: T = {
- val currentItems = current.get
- val newItems = currentItems match {
+ val currentItems: scala.collection.immutable.Seq[T] = current.get
+ val newItems: scala.collection.immutable.Seq[T] = currentItems match {
case Nil ⇒ items
case xs ⇒ xs
}
@@ -63,7 +63,7 @@ object TypedActorSpec {
def pigdog(): String
@throws(classOf[TimeoutException])
- def self = TypedActor.self[Foo]
+ def self: akka.actor.TypedActorSpec.Foo = TypedActor.self[Foo]
def futurePigdog(): Future[String]
@@ -127,7 +127,7 @@ object TypedActorSpec {
}
def futureComposePigdogFrom(foo: Foo): Future[String] = {
- implicit val timeout = TypedActor(TypedActor.context.system).DefaultReturnTimeout
+ implicit val timeout: akka.util.Timeout = TypedActor(TypedActor.context.system).DefaultReturnTimeout
foo.futurePigdog(500 millis).map(_.toUpperCase)
}
@@ -149,7 +149,7 @@ object TypedActorSpec {
internalNumber += 1
}
- def read() = internalNumber
+ def read(): Int = internalNumber
}
trait Stackable1 {
@@ -220,18 +220,18 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
TypedActor(system).typedActorOf(
TypedProps[StackedImpl](classOf[Stacked], classOf[StackedImpl]).withTimeout(timeout))
- def mustStop(typedActor: AnyRef) = TypedActor(system).stop(typedActor) should ===(true)
+ def mustStop(typedActor: AnyRef): org.scalatest.Assertion = TypedActor(system).stop(typedActor) should ===(true)
"TypedActors" must {
"be able to instantiate" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
TypedActor(system).isTypedActor(t) should ===(true)
mustStop(t)
}
"be able to stop" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
mustStop(t)
}
@@ -248,32 +248,32 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"have access to itself when executing a method call" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t.self should ===(t)
mustStop(t)
}
"be able to call toString" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t.toString should ===(TypedActor(system).getActorRefFor(t).toString)
mustStop(t)
}
"be able to call equals" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t should ===(t)
t should not equal (null)
mustStop(t)
}
"be able to call hashCode" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t.hashCode should ===(TypedActor(system).getActorRefFor(t).hashCode)
mustStop(t)
}
"be able to call user-defined void-methods" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t.incr()
t.read() should ===(1)
t.incr()
@@ -283,13 +283,13 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"be able to call normally returning methods" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t.pigdog() should ===("Pigdog")
mustStop(t)
}
"be able to call null returning methods" in {
- val t = newFooBar
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
t.nullJOption() should be(JOption.none)
t.nullOption() should ===(None)
t.nullReturn() should ===(null)
@@ -297,16 +297,16 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"be able to call Future-returning methods non-blockingly" in {
- val t = newFooBar
- val f = t.futurePigdog(200 millis)
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
+ val f: scala.concurrent.Future[String] = t.futurePigdog(200 millis)
f.isCompleted should ===(false)
Await.result(f, timeout.duration) should ===("Pigdog")
mustStop(t)
}
"be able to call multiple Future-returning methods non-blockingly" in within(timeout.duration) {
- val t = newFooBar
- val futures = for (i ← 1 to 20) yield (i, t.futurePigdog(20 millis, i))
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar
+ val futures: scala.collection.immutable.IndexedSeq[(Int, scala.concurrent.Future[String])] = for (i ← 1 to 20) yield (i, t.futurePigdog(20 millis, i))
for ((i, f) ← futures) {
Await.result(f, remaining) should ===("Pigdog" + i)
}
@@ -314,20 +314,20 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"be able to call methods returning Java Options" taggedAs TimingTest in {
- val t = newFooBar(1 second)
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar(1 second)
t.joptionPigdog(100 millis).get should ===("Pigdog")
t.joptionPigdog(2 seconds) should ===(JOption.none[String])
mustStop(t)
}
"be able to handle AskTimeoutException as None" taggedAs TimingTest in {
- val t = newFooBar(200 millis)
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar(200 millis)
t.joptionPigdog(600 millis) should ===(JOption.none[String])
mustStop(t)
}
"be able to call methods returning Scala Options" taggedAs TimingTest in {
- val t = newFooBar(1 second)
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar(1 second)
t.optionPigdog(100 millis).get should ===("Pigdog")
t.optionPigdog(2 seconds) should ===(None)
mustStop(t)
@@ -335,7 +335,7 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
"be able to compose futures without blocking" in within(timeout.duration) {
val t, t2 = newFooBar(remaining)
- val f = t.futureComposePigdogFrom(t2)
+ val f: scala.concurrent.Future[String] = t.futureComposePigdogFrom(t2)
f.isCompleted should ===(false)
Await.result(f, remaining) should ===("PIGDOG")
mustStop(t)
@@ -344,15 +344,15 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
"be able to handle exceptions when calling methods" in {
filterEvents(EventFilter[IllegalStateException]("expected")) {
- val boss = system.actorOf(Props(new Actor {
- override val supervisorStrategy = OneForOneStrategy() {
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case e: IllegalStateException if e.getMessage == "expected" ⇒ SupervisorStrategy.Resume
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case p: TypedProps[_] ⇒ context.sender() ! TypedActor(context).typedActorOf(p)
}
}))
- val t = Await.result((boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2 seconds)).mapTo[Foo], timeout.duration)
+ val t: akka.actor.TypedActorSpec.Foo = Await.result((boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2 seconds)).mapTo[Foo], timeout.duration)
t.incr()
t.failingPigdog()
@@ -374,7 +374,7 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
"be restarted on failure" in {
filterEvents(EventFilter[IllegalStateException]("expected")) {
- val t = newFooBar(Duration(2, "s"))
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar(Duration(2, "s"))
intercept[IllegalStateException] { t.failingOptionPigdog() }.getMessage should ===("expected")
t.optionPigdog() should ===(Some("Pigdog"))
mustStop(t)
@@ -388,7 +388,7 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"be able to support stacked traits for the interface part" in {
- val t = newStacked()
+ val t: akka.actor.TypedActorSpec.Stacked = newStacked()
t.notOverriddenStacked should ===("foobar")
t.stacked should ===("FOOBAR")
mustStop(t)
@@ -396,8 +396,8 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
"be able to support implementation only typed actors" in within(timeout.duration) {
val t: Foo = TypedActor(system).typedActorOf(TypedProps[Bar]())
- val f = t.futurePigdog(200 millis)
- val f2 = t.futurePigdog(Duration.Zero)
+ val f: scala.concurrent.Future[String] = t.futurePigdog(200 millis)
+ val f2: scala.concurrent.Future[String] = t.futurePigdog(Duration.Zero)
f2.isCompleted should ===(false)
f.isCompleted should ===(false)
Await.result(f, remaining) should ===(Await.result(f2, remaining))
@@ -412,10 +412,10 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"be able to use balancing dispatcher" in within(timeout.duration) {
- val thais = for (i ← 1 to 60) yield newFooBar("pooled-dispatcher", 6 seconds)
- val iterator = new CyclicIterator(thais)
+ val thais: scala.collection.immutable.IndexedSeq[akka.actor.TypedActorSpec.Foo] = for (i ← 1 to 60) yield newFooBar("pooled-dispatcher", 6 seconds)
+ val iterator: akka.actor.TypedActorSpec.CyclicIterator[akka.actor.TypedActorSpec.Foo] = new CyclicIterator(thais)
- val results = for (i ← 1 to 120) yield (i, iterator.next.futurePigdog(200 millis, i))
+ val results: scala.collection.immutable.IndexedSeq[(Int, scala.concurrent.Future[String])] = for (i ← 1 to 120) yield (i, iterator.next.futurePigdog(200 millis, i))
for ((i, r) ← results) Await.result(r, remaining) should ===("Pigdog" + i)
@@ -425,16 +425,16 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
"be able to serialize and deserialize invocations" in {
import java.io._
JavaSerializer.currentSystem.withValue(system.asInstanceOf[ExtendedActorSystem]) {
- val m = TypedActor.MethodCall(classOf[Foo].getDeclaredMethod("pigdog"), Array[AnyRef]())
- val baos = new ByteArrayOutputStream(8192 * 4)
- val out = new ObjectOutputStream(baos)
+ val m: akka.actor.TypedActor.MethodCall = TypedActor.MethodCall(classOf[Foo].getDeclaredMethod("pigdog"), Array[AnyRef]())
+ val baos: java.io.ByteArrayOutputStream = new ByteArrayOutputStream(8192 * 4)
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(baos)
out.writeObject(m)
out.close()
- val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
- val mNew = in.readObject().asInstanceOf[TypedActor.MethodCall]
+ val mNew: akka.actor.TypedActor.MethodCall = in.readObject().asInstanceOf[TypedActor.MethodCall]
mNew.method should ===(m.method)
}
@@ -444,16 +444,16 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
import java.io._
val someFoo: Foo = new Bar
JavaSerializer.currentSystem.withValue(system.asInstanceOf[ExtendedActorSystem]) {
- val m = TypedActor.MethodCall(classOf[Foo].getDeclaredMethod("testMethodCallSerialization", Array[Class[_]](classOf[Foo], classOf[String], classOf[Int]): _*), Array[AnyRef](someFoo, null, 1.asInstanceOf[AnyRef]))
- val baos = new ByteArrayOutputStream(8192 * 4)
- val out = new ObjectOutputStream(baos)
+ val m: akka.actor.TypedActor.MethodCall = TypedActor.MethodCall(classOf[Foo].getDeclaredMethod("testMethodCallSerialization", Array[Class[_]](classOf[Foo], classOf[String], classOf[Int]): _*), Array[AnyRef](someFoo, null, 1.asInstanceOf[AnyRef]))
+ val baos: java.io.ByteArrayOutputStream = new ByteArrayOutputStream(8192 * 4)
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(baos)
out.writeObject(m)
out.close()
- val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
- val mNew = in.readObject().asInstanceOf[TypedActor.MethodCall]
+ val mNew: akka.actor.TypedActor.MethodCall = in.readObject().asInstanceOf[TypedActor.MethodCall]
mNew.method should ===(m.method)
mNew.parameters should have size 3
@@ -468,19 +468,19 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
"be able to serialize and deserialize proxies" in {
import java.io._
JavaSerializer.currentSystem.withValue(system.asInstanceOf[ExtendedActorSystem]) {
- val t = newFooBar(Duration(2, "s"))
+ val t: akka.actor.TypedActorSpec.Foo = newFooBar(Duration(2, "s"))
t.optionPigdog() should ===(Some("Pigdog"))
- val baos = new ByteArrayOutputStream(8192 * 4)
- val out = new ObjectOutputStream(baos)
+ val baos: java.io.ByteArrayOutputStream = new ByteArrayOutputStream(8192 * 4)
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(baos)
out.writeObject(t)
out.close()
- val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
- val tNew = in.readObject().asInstanceOf[Foo]
+ val tNew: akka.actor.TypedActorSpec.Foo = in.readObject().asInstanceOf[Foo]
tNew should ===(t)
@@ -491,15 +491,15 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config)
}
"be able to override lifecycle callbacks" in {
- val latch = new CountDownLatch(16)
- val ta = TypedActor(system)
+ val latch: java.util.concurrent.CountDownLatch = new CountDownLatch(16)
+ val ta: akka.actor.TypedActorExtension = TypedActor(system)
val t: LifeCycles = ta.typedActorOf(TypedProps[LifeCyclesImpl](classOf[LifeCycles], new LifeCyclesImpl(latch)))
EventFilter[IllegalStateException]("Crash!", occurrences = 1) intercept {
t.crash()
}
//Sneak in a check for the Receiver override
- val ref = ta getActorRefFor t
+ val ref: akka.actor.ActorRef = ta getActorRefFor t
ref.tell("pigdog", testActor)
@@ -523,23 +523,23 @@ class TypedActorRouterSpec extends AkkaSpec(TypedActorSpec.config)
def newFooBar(d: FiniteDuration): Foo =
TypedActor(system).typedActorOf(TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(Timeout(d)))
- def mustStop(typedActor: AnyRef) = TypedActor(system).stop(typedActor) should ===(true)
+ def mustStop(typedActor: AnyRef): org.scalatest.Assertion = TypedActor(system).stop(typedActor) should ===(true)
"TypedActor Router" must {
"work" in {
- val t1 = newFooBar
- val t2 = newFooBar
- val t3 = newFooBar
- val t4 = newFooBar
- val routees = List(t1, t2, t3, t4) map { t ⇒ TypedActor(system).getActorRefFor(t).path.toStringWithoutAddress }
+ val t1: akka.actor.TypedActorSpec.Foo = newFooBar
+ val t2: akka.actor.TypedActorSpec.Foo = newFooBar
+ val t3: akka.actor.TypedActorSpec.Foo = newFooBar
+ val t4: akka.actor.TypedActorSpec.Foo = newFooBar
+ val routees: List[String] = List(t1, t2, t3, t4) map { t ⇒ TypedActor(system).getActorRefFor(t).path.toStringWithoutAddress }
TypedActor(system).isTypedActor(t1) should ===(true)
TypedActor(system).isTypedActor(t2) should ===(true)
- val router = system.actorOf(RoundRobinGroup(routees).props(), "router")
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinGroup(routees).props(), "router")
- val typedRouter = TypedActor(system).typedActorOf[Foo, Foo](TypedProps[Foo](), router)
+ val typedRouter: akka.actor.TypedActorSpec.Foo = TypedActor(system).typedActorOf[Foo, Foo](TypedProps[Foo](), router)
info("got = " + typedRouter.optionPigdog())
info("got = " + typedRouter.optionPigdog())
diff --git a/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala b/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala
index 5b8d42a..4e67883 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala
@@ -36,7 +36,7 @@ object UidClashTest {
class RestartedActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case PleaseRestart ⇒ throw new Exception("restart")
case Terminated(ref) ⇒ throw new TerminatedForNonWatchedActor
// This is the tricky part to make this test a positive one (avoid expectNoMsg).
@@ -67,15 +67,15 @@ object UidClashTest {
}
class RestartingActor(probe: ActorRef) extends Actor {
- override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) {
+ override val supervisorStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy(loggingEnabled = false) {
case _: TerminatedForNonWatchedActor ⇒
context.stop(self)
Stop
case _ ⇒ Restart
}
- val theRestartedOne = context.actorOf(Props[RestartedActor], "theRestartedOne")
+ val theRestartedOne: akka.actor.ActorRef = context.actorOf(Props[RestartedActor], "theRestartedOne")
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case PleaseRestart ⇒ theRestartedOne ! PleaseRestart
case RestartedSafely ⇒ probe ! RestartedSafely
}
@@ -88,8 +88,8 @@ class UidClashTest extends AkkaSpec {
"The Terminated message for an old child stopped in preRestart" should {
"not arrive after restart" in {
- val watcher = TestProbe()
- val topActor = system.actorOf(Props(classOf[RestartingActor], watcher.ref), "top")
+ val watcher: akka.testkit.TestProbe = TestProbe()
+ val topActor: akka.actor.ActorRef = system.actorOf(Props(classOf[RestartingActor], watcher.ref), "top")
watcher.watch(topActor)
topActor ! PleaseRestart
diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala
index 0157f65..1c0b654 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala
@@ -64,7 +64,7 @@ object ActorModelSpec {
class DispatcherActor extends Actor {
private val busy = new Switch(false)
- def interceptor = context.dispatcher.asInstanceOf[MessageDispatcherInterceptor]
+ def interceptor: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = context.dispatcher.asInstanceOf[MessageDispatcherInterceptor]
def ack(): Unit = {
if (!busy.switchOn(())) {
@@ -78,7 +78,7 @@ object ActorModelSpec {
interceptor.getStats(self).restarts.incrementAndGet()
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case AwaitLatch(latch) ⇒ { ack(); latch.await(); busy.switchOff(()) }
case Meet(sign, wait) ⇒ { ack(); sign.countDown(); wait.await(); busy.switchOff(()) }
case Wait(time) ⇒ { ack(); Thread.sleep(time); busy.switchOff(()) }
@@ -98,26 +98,26 @@ object ActorModelSpec {
}
class InterceptorStats {
- val suspensions = new AtomicLong(0)
- val resumes = new AtomicLong(0)
- val registers = new AtomicLong(0)
- val unregisters = new AtomicLong(0)
- val msgsReceived = new AtomicLong(0)
- val msgsProcessed = new AtomicLong(0)
- val restarts = new AtomicLong(0)
- override def toString = "InterceptorStats(susp=" + suspensions +
+ val suspensions: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ val resumes: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ val registers: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ val unregisters: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ val msgsReceived: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ val msgsProcessed: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ val restarts: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
+ override def toString: String = "InterceptorStats(susp=" + suspensions +
",res=" + resumes + ",reg=" + registers + ",unreg=" + unregisters +
",recv=" + msgsReceived + ",proc=" + msgsProcessed + ",restart=" + restarts
}
trait MessageDispatcherInterceptor extends MessageDispatcher {
- val stats = new ConcurrentHashMap[ActorRef, InterceptorStats]
- val stops = new AtomicLong(0)
+ val stats: java.util.concurrent.ConcurrentHashMap[akka.actor.ActorRef, akka.actor.dispatch.ActorModelSpec.InterceptorStats] = new ConcurrentHashMap[ActorRef, InterceptorStats]
+ val stops: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
- def getStats(actorRef: ActorRef) = {
+ def getStats(actorRef: ActorRef): akka.actor.dispatch.ActorModelSpec.InterceptorStats = {
stats.get(actorRef) match {
case null ⇒
- val is = new InterceptorStats
+ val is: akka.actor.dispatch.ActorModelSpec.InterceptorStats = new InterceptorStats
stats.putIfAbsent(actorRef, is) match {
case null ⇒ is
case other ⇒ other
@@ -148,7 +148,7 @@ object ActorModelSpec {
}
protected[akka] abstract override def dispatch(receiver: ActorCell, invocation: Envelope) {
- val stats = getStats(receiver.self)
+ val stats: akka.actor.dispatch.ActorModelSpec.InterceptorStats = getStats(receiver.self)
stats.msgsReceived.incrementAndGet()
super.dispatch(receiver, invocation)
}
@@ -161,7 +161,7 @@ object ActorModelSpec {
def assertDispatcher(dispatcher: MessageDispatcherInterceptor)(
stops: Long = dispatcher.stops.get())(implicit system: ActorSystem) {
- val deadline = System.currentTimeMillis + dispatcher.shutdownTimeout.toMillis * 5
+ val deadline: Long = System.currentTimeMillis + dispatcher.shutdownTimeout.toMillis * 5
try {
await(deadline)(stops == dispatcher.stops.get)
} catch {
@@ -182,7 +182,7 @@ object ActorModelSpec {
fail("Expected count down to fail after " + wait + " millis. " + hint)
}
- def statsFor(actorRef: ActorRef, dispatcher: MessageDispatcher = null) =
+ def statsFor(actorRef: ActorRef, dispatcher: MessageDispatcher = null): akka.actor.dispatch.ActorModelSpec.InterceptorStats =
dispatcher.asInstanceOf[MessageDispatcherInterceptor].getStats(actorRef)
def assertRefDefaultZero(actorRef: ActorRef, dispatcher: MessageDispatcher = null)(
@@ -211,8 +211,8 @@ object ActorModelSpec {
msgsReceived: Long = statsFor(actorRef, dispatcher).msgsReceived.get(),
msgsProcessed: Long = statsFor(actorRef, dispatcher).msgsProcessed.get(),
restarts: Long = statsFor(actorRef, dispatcher).restarts.get())(implicit system: ActorSystem) {
- val stats = statsFor(actorRef, Option(dispatcher).getOrElse(actorRef.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].dispatcher))
- val deadline = System.currentTimeMillis + 1000
+ val stats: akka.actor.dispatch.ActorModelSpec.InterceptorStats = statsFor(actorRef, Option(dispatcher).getOrElse(actorRef.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].dispatcher))
+ val deadline: Long = System.currentTimeMillis + 1000
try {
await(deadline)(stats.suspensions.get() == suspensions)
await(deadline)(stats.resumes.get() == resumes)
@@ -251,7 +251,7 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
import ActorModelSpec._
- def newTestActor(dispatcher: String) = system.actorOf(Props[DispatcherActor].withDispatcher(dispatcher))
+ def newTestActor(dispatcher: String): akka.actor.ActorRef = system.actorOf(Props[DispatcherActor].withDispatcher(dispatcher))
def awaitStarted(ref: ActorRef): Unit = {
awaitCond(ref match {
@@ -266,9 +266,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
"A " + dispatcherType must {
"dynamically handle its own life cycle" in {
- implicit val dispatcher = interceptedDispatcher()
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
assertDispatcher(dispatcher)(stops = 0)
- val a = newTestActor(dispatcher.id)
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
assertDispatcher(dispatcher)(stops = 0)
system.stop(a)
assertDispatcher(dispatcher)(stops = 1)
@@ -281,13 +281,13 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
msgsProcessed = 0,
restarts = 0)
- val futures = for (i ← 1 to 10) yield Future {
+ val futures: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[Int]] = for (i ← 1 to 10) yield Future {
i
}
assertDispatcher(dispatcher)(stops = 2)
- val a2 = newTestActor(dispatcher.id)
- val futures2 = for (i ← 1 to 10) yield Future { i }
+ val a2: akka.actor.ActorRef = newTestActor(dispatcher.id)
+ val futures2: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[Int]] = for (i ← 1 to 10) yield Future { i }
assertDispatcher(dispatcher)(stops = 2)
@@ -296,9 +296,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
}
"process messages one at a time" in {
- implicit val dispatcher = interceptedDispatcher()
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
val start, oneAtATime = new CountDownLatch(1)
- val a = newTestActor(dispatcher.id)
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
awaitStarted(a)
a ! CountDown(start)
@@ -316,9 +316,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
}
"handle queueing from multiple threads" in {
- implicit val dispatcher = interceptedDispatcher()
- val counter = new CountDownLatch(200)
- val a = newTestActor(dispatcher.id)
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
+ val counter: java.util.concurrent.CountDownLatch = new CountDownLatch(200)
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
for (i ← 1 to 10) {
spawn {
@@ -343,10 +343,10 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
}
"not process messages for a suspended actor" in {
- implicit val dispatcher = interceptedDispatcher()
- val a = newTestActor(dispatcher.id).asInstanceOf[InternalActorRef]
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
+ val a: akka.actor.InternalActorRef = newTestActor(dispatcher.id).asInstanceOf[InternalActorRef]
awaitStarted(a)
- val done = new CountDownLatch(1)
+ val done: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
a.suspend
a ! CountDown(done)
assertNoCountDown(done, 1000, "Should not process messages while suspended")
@@ -363,16 +363,16 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
}
"handle waves of actors" in {
- val dispatcher = interceptedDispatcher()
- val props = Props[DispatcherActor].withDispatcher(dispatcher.id)
+ val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
+ val props: akka.actor.Props = Props[DispatcherActor].withDispatcher(dispatcher.id)
def flood(num: Int) {
- val cachedMessage = CountDownNStop(new CountDownLatch(num))
- val stopLatch = new CountDownLatch(num)
- val keepAliveLatch = new CountDownLatch(1)
- val waitTime = (20 seconds).dilated.toMillis
- val boss = system.actorOf(Props(new Actor {
- def receive = {
+ val cachedMessage: akka.actor.dispatch.ActorModelSpec.CountDownNStop = CountDownNStop(new CountDownLatch(num))
+ val stopLatch: java.util.concurrent.CountDownLatch = new CountDownLatch(num)
+ val keepAliveLatch: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val waitTime: Long = (20 seconds).dilated.toMillis
+ val boss: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "run" ⇒ for (_ ← 1 to num) (context.watch(context.actorOf(props))) ! cachedMessage
case Terminated(child) ⇒ stopLatch.countDown()
}
@@ -382,7 +382,7 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
// the boss doesn't create children fast enough to keep the dispatcher from becoming empty
// and it needs to be on a separate thread to not deadlock the calling thread dispatcher
new Thread(new Runnable {
- def run() = Future {
+ def run(): Unit = Future {
keepAliveLatch.await(waitTime, TimeUnit.MILLISECONDS)
}(dispatcher)
}).start()
@@ -393,12 +393,12 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
case e: Throwable ⇒
dispatcher match {
case dispatcher: BalancingDispatcher ⇒
- val team = dispatcher.team
- val mq = dispatcher.messageQueue
+ val team: java.util.concurrent.ConcurrentSkipListSet[akka.actor.ActorCell] = dispatcher.team
+ val mq: akka.dispatch.MessageQueue = dispatcher.messageQueue
System.err.println("Teammates left: " + team.size + " stopLatch: " + stopLatch.getCount + " inhab:" + dispatcher.inhabitants)
team.toArray sorted new Ordering[AnyRef] {
- def compare(l: AnyRef, r: AnyRef) = (l, r) match { case (ll: ActorCell, rr: ActorCell) ⇒ ll.self.path compareTo rr.self.path }
+ def compare(l: AnyRef, r: AnyRef): Int = (l, r) match { case (ll: ActorCell, rr: ActorCell) ⇒ ll.self.path compareTo rr.self.path }
} foreach {
case cell: ActorCell ⇒
System.err.println(" - " + cell.self.path + " " + cell.isTerminated + " " + cell.mailbox.currentStatus + " "
@@ -429,18 +429,18 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
EventFilter[InterruptedException](),
EventFilter[ActorInterruptedException](),
EventFilter[akka.event.Logging.LoggerException]()) {
- implicit val dispatcher = interceptedDispatcher()
- val a = newTestActor(dispatcher.id)
- val f1 = a ? Reply("foo")
- val f2 = a ? Reply("bar")
- val f3 = a ? Interrupt
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
+ val f1: scala.concurrent.Future[Any] = a ? Reply("foo")
+ val f2: scala.concurrent.Future[Any] = a ? Reply("bar")
+ val f3: scala.concurrent.Future[Any] = a ? Interrupt
Thread.interrupted() // CallingThreadDispatcher may necessitate this
- val f4 = a ? Reply("foo2")
- val f5 = a ? Interrupt
+ val f4: scala.concurrent.Future[Any] = a ? Reply("foo2")
+ val f5: scala.concurrent.Future[Any] = a ? Interrupt
Thread.interrupted() // CallingThreadDispatcher may necessitate this
- val f6 = a ? Reply("bar2")
+ val f6: scala.concurrent.Future[Any] = a ? Reply("bar2")
- val c = system.scheduler.scheduleOnce(2.seconds) {
+ val c: akka.actor.Cancellable = system.scheduler.scheduleOnce(2.seconds) {
import collection.JavaConverters._
Thread.getAllStackTraces().asScala foreach {
case (thread, stack) ⇒
@@ -461,14 +461,14 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
"continue to process messages without failure when a thread gets interrupted and doesn't throw an exception" in {
filterEvents(EventFilter[InterruptedException]()) {
- implicit val dispatcher = interceptedDispatcher()
- val a = newTestActor(dispatcher.id)
- val f1 = a ? Reply("foo")
- val f2 = a ? Reply("bar")
- val f3 = a ? InterruptNicely("baz")
- val f4 = a ? Reply("foo2")
- val f5 = a ? InterruptNicely("baz2")
- val f6 = a ? Reply("bar2")
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
+ val f1: scala.concurrent.Future[Any] = a ? Reply("foo")
+ val f2: scala.concurrent.Future[Any] = a ? Reply("bar")
+ val f3: scala.concurrent.Future[Any] = a ? InterruptNicely("baz")
+ val f4: scala.concurrent.Future[Any] = a ? Reply("foo2")
+ val f5: scala.concurrent.Future[Any] = a ? InterruptNicely("baz2")
+ val f6: scala.concurrent.Future[Any] = a ? Reply("bar2")
assert(Await.result(f1, timeout.duration) === "foo")
assert(Await.result(f2, timeout.duration) === "bar")
@@ -483,14 +483,14 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
"continue to process messages when exception is thrown" in {
filterEvents(EventFilter[IndexOutOfBoundsException](), EventFilter[RemoteException]()) {
- implicit val dispatcher = interceptedDispatcher()
- val a = newTestActor(dispatcher.id)
- val f1 = a ? Reply("foo")
- val f2 = a ? Reply("bar")
- val f3 = a ? ThrowException(new IndexOutOfBoundsException("IndexOutOfBoundsException"))
- val f4 = a ? Reply("foo2")
- val f5 = a ? ThrowException(new RemoteException("RemoteException"))
- val f6 = a ? Reply("bar2")
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
+ val f1: scala.concurrent.Future[Any] = a ? Reply("foo")
+ val f2: scala.concurrent.Future[Any] = a ? Reply("bar")
+ val f3: scala.concurrent.Future[Any] = a ? ThrowException(new IndexOutOfBoundsException("IndexOutOfBoundsException"))
+ val f4: scala.concurrent.Future[Any] = a ? Reply("foo2")
+ val f5: scala.concurrent.Future[Any] = a ? ThrowException(new RemoteException("RemoteException"))
+ val f6: scala.concurrent.Future[Any] = a ? Reply("bar2")
assert(Await.result(f1, timeout.duration) === "foo")
assert(Await.result(f2, timeout.duration) === "bar")
@@ -502,9 +502,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
}
"not double-deregister" in {
- implicit val dispatcher = interceptedDispatcher()
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
for (i ← 1 to 1000) system.actorOf(Props.empty)
- val a = newTestActor(dispatcher.id)
+ val a: akka.actor.ActorRef = newTestActor(dispatcher.id)
a ! DoubleStop
awaitCond(statsFor(a, dispatcher).registers.get == 1)
awaitCond(statsFor(a, dispatcher).unregisters.get == 1)
@@ -515,7 +515,7 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
object DispatcherModelSpec {
import ActorModelSpec._
- val config = {
+ val config: String = {
"""
boss {
executor = thread-pool-executor
@@ -550,7 +550,7 @@ object DispatcherModelSpec {
class DispatcherModelSpec extends ActorModelSpec(DispatcherModelSpec.config) {
import ActorModelSpec._
- val dispatcherCount = new AtomicInteger()
+ val dispatcherCount: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger()
override def interceptedDispatcher(): MessageDispatcherInterceptor = {
// use new id for each test, since the MessageDispatcherInterceptor holds state
@@ -561,7 +561,7 @@ class DispatcherModelSpec extends ActorModelSpec(DispatcherModelSpec.config) {
"A " + dispatcherType must {
"process messages in parallel" in {
- implicit val dispatcher = interceptedDispatcher()
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
val aStart, aStop, bParallel = new CountDownLatch(1)
val a, b = newTestActor(dispatcher.id)
@@ -588,7 +588,7 @@ object BalancingDispatcherModelSpec {
import ActorModelSpec._
// TODO check why throughput=1 here? (came from old test)
- val config = {
+ val config: String = {
"""
boss {
executor = thread-pool-executor
@@ -624,7 +624,7 @@ object BalancingDispatcherModelSpec {
class BalancingDispatcherModelSpec extends ActorModelSpec(BalancingDispatcherModelSpec.config) {
import ActorModelSpec._
- val dispatcherCount = new AtomicInteger()
+ val dispatcherCount: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger()
override def interceptedDispatcher(): MessageDispatcherInterceptor = {
// use new id for each test, since the MessageDispatcherInterceptor holds state
@@ -635,7 +635,7 @@ class BalancingDispatcherModelSpec extends ActorModelSpec(BalancingDispatcherMod
"A " + dispatcherType must {
"process messages in parallel" in {
- implicit val dispatcher = interceptedDispatcher()
+ implicit val dispatcher: akka.actor.dispatch.ActorModelSpec.MessageDispatcherInterceptor = interceptedDispatcher()
val aStart, aStop, bParallel = new CountDownLatch(1)
val a, b = newTestActor(dispatcher.id)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala
index 52f7831..35dea5a 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala
@@ -23,7 +23,7 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) {
@volatile
var invocationCount = 0
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x: Int ⇒ {
Thread.sleep(delay)
invocationCount += 1
@@ -33,15 +33,15 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) {
}
class FirstActor extends Actor {
- def receive = { case _ ⇒ {} }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ {} }
}
class SecondActor extends Actor {
- def receive = { case _ ⇒ {} }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ {} }
}
class ParentActor extends Actor {
- def receive = { case _ ⇒ {} }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ {} }
}
class ChildActor extends ParentActor {
@@ -49,10 +49,10 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) {
"A BalancingDispatcher" must {
"have fast actor stealing work from slow actor" in {
- val finishedCounter = new CountDownLatch(110)
+ val finishedCounter: java.util.concurrent.CountDownLatch = new CountDownLatch(110)
- val slow = system.actorOf(Props(new DelayableActor(50, finishedCounter)).withDispatcher(delayableActorDispatcher)).asInstanceOf[ActorRefWithCell]
- val fast = system.actorOf(Props(new DelayableActor(10, finishedCounter)).withDispatcher(delayableActorDispatcher)).asInstanceOf[ActorRefWithCell]
+ val slow: akka.actor.ActorRefWithCell = system.actorOf(Props(new DelayableActor(50, finishedCounter)).withDispatcher(delayableActorDispatcher)).asInstanceOf[ActorRefWithCell]
+ val fast: akka.actor.ActorRefWithCell = system.actorOf(Props(new DelayableActor(10, finishedCounter)).withDispatcher(delayableActorDispatcher)).asInstanceOf[ActorRefWithCell]
var sentToFast = 0
diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala
index 6a10473..7c63597 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala
@@ -33,17 +33,17 @@ object DispatcherActorSpec {
"""
class TestActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "Hello" ⇒ sender() ! "World"
case "Failure" ⇒ throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
object OneWayTestActor {
- val oneWay = new CountDownLatch(1)
+ val oneWay: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
}
class OneWayTestActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "OneWay" ⇒ OneWayTestActor.oneWay.countDown()
}
}
@@ -57,14 +57,14 @@ class DispatcherActorSpec extends AkkaSpec(DispatcherActorSpec.config) with Defa
"A Dispatcher and an Actor" must {
"support tell" in {
- val actor = system.actorOf(Props[OneWayTestActor].withDispatcher("test-dispatcher"))
- val result = actor ! "OneWay"
+ val actor: akka.actor.ActorRef = system.actorOf(Props[OneWayTestActor].withDispatcher("test-dispatcher"))
+ val result: Unit = actor ! "OneWay"
assert(OneWayTestActor.oneWay.await(1, TimeUnit.SECONDS))
system.stop(actor)
}
"support ask/reply" in {
- val actor = system.actorOf(Props[TestActor].withDispatcher("test-dispatcher"))
+ val actor: akka.actor.ActorRef = system.actorOf(Props[TestActor].withDispatcher("test-dispatcher"))
assert("World" === Await.result(actor ? "Hello", timeout.duration))
system.stop(actor)
}
@@ -72,16 +72,16 @@ class DispatcherActorSpec extends AkkaSpec(DispatcherActorSpec.config) with Defa
"respect the throughput setting" in {
val throughputDispatcher = "test-throughput-dispatcher"
- val works = new AtomicBoolean(true)
- val latch = new CountDownLatch(100)
- val start = new CountDownLatch(1)
- val fastOne = system.actorOf(
- Props(new Actor { def receive = { case "sabotage" ⇒ works.set(false) } })
+ val works: java.util.concurrent.atomic.AtomicBoolean = new AtomicBoolean(true)
+ val latch: java.util.concurrent.CountDownLatch = new CountDownLatch(100)
+ val start: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val fastOne: akka.actor.ActorRef = system.actorOf(
+ Props(new Actor { def receive: PartialFunction[Any, Unit] = { case "sabotage" ⇒ works.set(false) } })
.withDispatcher(throughputDispatcher))
- val slowOne = system.actorOf(
+ val slowOne: akka.actor.ActorRef = system.actorOf(
Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "hogexecutor" ⇒ { sender() ! "OK"; start.await }
case "ping" ⇒ if (works.get) latch.countDown()
}
@@ -98,24 +98,24 @@ class DispatcherActorSpec extends AkkaSpec(DispatcherActorSpec.config) with Defa
}
"respect throughput deadline" in {
- val deadline = 100 millis
+ val deadline: scala.concurrent.duration.FiniteDuration = 100 millis
val throughputDispatcher = "test-throughput-deadline-dispatcher"
- val works = new AtomicBoolean(true)
- val latch = new CountDownLatch(1)
- val start = new CountDownLatch(1)
- val ready = new CountDownLatch(1)
+ val works: java.util.concurrent.atomic.AtomicBoolean = new AtomicBoolean(true)
+ val latch: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val start: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val ready: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
- val fastOne = system.actorOf(
+ val fastOne: akka.actor.ActorRef = system.actorOf(
Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "ping" ⇒ if (works.get) latch.countDown(); context.stop(self)
}
}).withDispatcher(throughputDispatcher))
- val slowOne = system.actorOf(
+ val slowOne: akka.actor.ActorRef = system.actorOf(
Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "hogexecutor" ⇒ { ready.countDown(); start.await }
case "ping" ⇒ { works.set(false); context.stop(self) }
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala
index 9e76383..066d6a7 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala
@@ -10,7 +10,7 @@ import akka.testkit.AkkaSpec
class DispatcherActorsSpec extends AkkaSpec {
class SlowActor(finishedCounter: CountDownLatch) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x: Int ⇒ {
Thread.sleep(50) // slow actor
finishedCounter.countDown()
@@ -19,7 +19,7 @@ class DispatcherActorsSpec extends AkkaSpec {
}
class FastActor(finishedCounter: CountDownLatch) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x: Int ⇒ {
finishedCounter.countDown()
}
@@ -28,10 +28,10 @@ class DispatcherActorsSpec extends AkkaSpec {
"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)))
+ val sFinished: java.util.concurrent.CountDownLatch = new CountDownLatch(50)
+ val fFinished: java.util.concurrent.CountDownLatch = new CountDownLatch(10)
+ val s: akka.actor.ActorRef = system.actorOf(Props(new SlowActor(sFinished)))
+ val f: akka.actor.ActorRef = system.actorOf(Props(new FastActor(fFinished)))
// send a lot of stuff to s
for (i ← 1 to 50) {
diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala
index 7eb7cce..0d6792c 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala
@@ -63,15 +63,15 @@ object DispatchersSpec {
"""
class ThreadNameEcho extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case _ ⇒ sender() ! Thread.currentThread.getName
}
}
class OneShotMailboxType(settings: ActorSystem.Settings, config: Config)
extends MailboxType with ProducesMessageQueue[DoublingMailbox] {
- val created = new AtomicBoolean(false)
- override def create(owner: Option[ActorRef], system: Option[ActorSystem]) =
+ val created: java.util.concurrent.atomic.AtomicBoolean = new AtomicBoolean(false)
+ override def create(owner: Option[ActorRef], system: Option[ActorSystem]): akka.dispatch.MessageQueue =
if (created.compareAndSet(false, true)) {
new DoublingMailbox(owner)
} else
@@ -79,7 +79,7 @@ object DispatchersSpec {
}
class DoublingMailbox(owner: Option[ActorRef]) extends UnboundedQueueBasedMessageQueue {
- final val queue = new ConcurrentLinkedQueue[Envelope]()
+ final val queue: java.util.concurrent.ConcurrentLinkedQueue[akka.dispatch.Envelope] = new ConcurrentLinkedQueue[Envelope]()
override def enqueue(receiver: ActorRef, handle: Envelope): Unit = {
queue add handle
queue add handle
@@ -89,13 +89,13 @@ object DispatchersSpec {
// Workaround to narrow the type of unapplySeq of Regex since the unapplySeq(Any) will be removed in Scala 2.13
case class R(s: String) {
private val r = s.r
- def unapplySeq(arg: CharSequence) = r.unapplySeq(arg)
+ def unapplySeq(arg: CharSequence): Option[List[String]] = r.unapplySeq(arg)
}
}
class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSender {
import DispatchersSpec._
- val df = system.dispatchers
+ val df: akka.dispatch.Dispatchers = system.dispatchers
import df._
val tipe = "type"
@@ -113,9 +113,9 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"PinnedDispatcher" → ofType[PinnedDispatcher],
"Dispatcher" → ofType[Dispatcher])
- def validTypes = typesAndValidators.keys.toList
+ def validTypes: List[String] = typesAndValidators.keys.toList
- val defaultDispatcherConfig = settings.config.getConfig("akka.actor.default-dispatcher")
+ val defaultDispatcherConfig: com.typesafe.config.Config = settings.config.getConfig("akka.actor.default-dispatcher")
lazy val allDispatchers: Map[String, MessageDispatcher] = {
validTypes.map(t ⇒ (t, from(ConfigFactory.parseMap(Map(tipe → t, id → t).asJava).
@@ -124,7 +124,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
def assertMyDispatcherIsUsed(actor: ActorRef): Unit = {
actor ! "what's the name?"
- val Expected = R("(DispatchersSpec-myapp.mydispatcher-[1-9][0-9]*)")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("(DispatchersSpec-myapp.mydispatcher-[1-9][0-9]*)")
expectMsgPF() {
case Expected(x) ⇒
}
@@ -133,12 +133,12 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"Dispatchers" must {
"use defined properties" in {
- val dispatcher = lookup("myapp.mydispatcher")
+ val dispatcher: akka.dispatch.MessageDispatcher = lookup("myapp.mydispatcher")
dispatcher.throughput should ===(17)
}
"use specific id" in {
- val dispatcher = lookup("myapp.mydispatcher")
+ val dispatcher: akka.dispatch.MessageDispatcher = lookup("myapp.mydispatcher")
dispatcher.id should ===("myapp.mydispatcher")
}
@@ -149,7 +149,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
}
"have only one default dispatcher" in {
- val dispatcher = lookup(Dispatchers.DefaultDispatcherId)
+ val dispatcher: akka.dispatch.MessageDispatcher = lookup(Dispatchers.DefaultDispatcherId)
dispatcher should ===(defaultGlobalDispatcher)
dispatcher should ===(system.dispatcher)
}
@@ -167,8 +167,8 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
}
"provide lookup of dispatchers by id" in {
- val d1 = lookup("myapp.mydispatcher")
- val d2 = lookup("myapp.mydispatcher")
+ val d1: akka.dispatch.MessageDispatcher = lookup("myapp.mydispatcher")
+ val d2: akka.dispatch.MessageDispatcher = lookup("myapp.mydispatcher")
d1 should ===(d2)
}
@@ -178,7 +178,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"include system name and dispatcher id in thread names for thread-pool-executor" in {
system.actorOf(Props[ThreadNameEcho].withDispatcher("myapp.thread-pool-dispatcher")) ! "what's the name?"
- val Expected = R("(DispatchersSpec-myapp.thread-pool-dispatcher-[1-9][0-9]*)")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("(DispatchersSpec-myapp.thread-pool-dispatcher-[1-9][0-9]*)")
expectMsgPF() {
case Expected(x) ⇒
}
@@ -186,7 +186,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"include system name and dispatcher id in thread names for default-dispatcher" in {
system.actorOf(Props[ThreadNameEcho]) ! "what's the name?"
- val Expected = R("(DispatchersSpec-akka.actor.default-dispatcher-[1-9][0-9]*)")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("(DispatchersSpec-akka.actor.default-dispatcher-[1-9][0-9]*)")
expectMsgPF() {
case Expected(x) ⇒
}
@@ -194,7 +194,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"include system name and dispatcher id in thread names for pinned dispatcher" in {
system.actorOf(Props[ThreadNameEcho].withDispatcher("myapp.my-pinned-dispatcher")) ! "what's the name?"
- val Expected = R("(DispatchersSpec-myapp.my-pinned-dispatcher-[1-9][0-9]*)")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("(DispatchersSpec-myapp.my-pinned-dispatcher-[1-9][0-9]*)")
expectMsgPF() {
case Expected(x) ⇒
}
@@ -202,7 +202,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"include system name and dispatcher id in thread names for balancing dispatcher" in {
system.actorOf(Props[ThreadNameEcho].withDispatcher("myapp.balancing-dispatcher")) ! "what's the name?"
- val Expected = R("(DispatchersSpec-myapp.balancing-dispatcher-[1-9][0-9]*)")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("(DispatchersSpec-myapp.balancing-dispatcher-[1-9][0-9]*)")
expectMsgPF() {
case Expected(x) ⇒
}
@@ -218,11 +218,11 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
}
"use pool-dispatcher router of deployment config" in {
- val pool = system.actorOf(FromConfig.props(Props[ThreadNameEcho]), name = "pool1")
+ val pool: akka.actor.ActorRef = system.actorOf(FromConfig.props(Props[ThreadNameEcho]), name = "pool1")
pool ! Identify(None)
- val routee = expectMsgType[ActorIdentity].ref.get
+ val routee: akka.actor.ActorRef = expectMsgType[ActorIdentity].ref.get
routee ! "what's the name?"
- val Expected = R("""(DispatchersSpec-akka\.actor\.deployment\./pool1\.pool-dispatcher-[1-9][0-9]*)""")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("""(DispatchersSpec-akka\.actor\.deployment\./pool1\.pool-dispatcher-[1-9][0-9]*)""")
expectMsgPF() {
case Expected(x) ⇒
}
@@ -230,7 +230,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
"use balancing-pool router with special routees mailbox of deployment config" in {
system.actorOf(FromConfig.props(Props[ThreadNameEcho]), name = "balanced") ! "what's the name?"
- val Expected = R("""(DispatchersSpec-BalancingPool-/balanced-[1-9][0-9]*)""")
+ val Expected: akka.actor.dispatch.DispatchersSpec.R = R("""(DispatchersSpec-BalancingPool-/balanced-[1-9][0-9]*)""")
expectMsgPF() {
case Expected(x) ⇒
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala
index dd2f239..e5f3dc2 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala
@@ -18,7 +18,7 @@ object PinnedActorSpec {
"""
class TestActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "Hello" ⇒ sender() ! "World"
case "Failure" ⇒ throw new RuntimeException("Expected exception; to test fault-tolerance")
}
@@ -34,14 +34,14 @@ class PinnedActorSpec extends AkkaSpec(PinnedActorSpec.config) with BeforeAndAft
"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"
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case "OneWay" ⇒ oneWay.countDown() } }).withDispatcher("pinned-dispatcher"))
+ val result: Unit = actor ! "OneWay"
assert(oneWay.await(1, TimeUnit.SECONDS))
system.stop(actor)
}
"support ask/reply" in {
- val actor = system.actorOf(Props[TestActor].withDispatcher("pinned-dispatcher"))
+ val actor: akka.actor.ActorRef = system.actorOf(Props[TestActor].withDispatcher("pinned-dispatcher"))
assert("World" === Await.result(actor ? "Hello", timeout.duration))
system.stop(actor)
}
diff --git a/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala
index 6272cdd..b911094 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala
@@ -11,18 +11,18 @@ class ListenerSpec extends AkkaSpec {
"Listener" must {
"listen" in {
- val fooLatch = TestLatch(2)
- val barLatch = TestLatch(2)
- val barCount = new AtomicInteger(0)
+ val fooLatch: akka.testkit.TestLatch = TestLatch(2)
+ val barLatch: akka.testkit.TestLatch = TestLatch(2)
+ val barCount: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
- val broadcast = system.actorOf(Props(new Actor with Listeners {
- def receive = listenerManagement orElse {
+ val broadcast: akka.actor.ActorRef = system.actorOf(Props(new Actor with Listeners {
+ def receive: PartialFunction[Any, Unit] = listenerManagement orElse {
case "foo" ⇒ gossip("bar")
}
}))
- def newListener = system.actorOf(Props(new Actor {
- def receive = {
+ def newListener: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "bar" ⇒
barCount.incrementAndGet
barLatch.countDown()
@@ -31,9 +31,9 @@ class ListenerSpec extends AkkaSpec {
}
}))
- val a1 = newListener
- val a2 = newListener
- val a3 = newListener
+ val a1: akka.actor.ActorRef = newListener
+ val a2: akka.actor.ActorRef = newListener
+ val a3: akka.actor.ActorRef = newListener
broadcast ! Listen(a1)
broadcast ! Listen(a2)
diff --git a/akka-actor-tests/src/test/scala/akka/actor/setup/ActorSystemSetupSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/setup/ActorSystemSetupSpec.scala
index 1edec25..d2ee053 100644
--- a/akka-actor-tests/src/test/scala/akka/actor/setup/ActorSystemSetupSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/actor/setup/ActorSystemSetupSpec.scala
@@ -16,8 +16,8 @@ class ActorSystemSetupSpec extends WordSpec with Matchers {
"The ActorSystemSettings" should {
"store and retrieve a setup" in {
- val setup = DummySetup("Al Dente")
- val setups = ActorSystemSetup()
+ val setup: akka.actor.setup.DummySetup = DummySetup("Al Dente")
+ val setups: akka.actor.setup.ActorSystemSetup = ActorSystemSetup()
.withSetup(setup)
setups.get[DummySetup] should ===(Some(setup))
@@ -25,9 +25,9 @@ class ActorSystemSetupSpec extends WordSpec with Matchers {
}
"replace setup if already defined" in {
- val setup1 = DummySetup("Al Dente")
- val setup2 = DummySetup("Earl E. Bird")
- val setups = ActorSystemSetup()
+ val setup1: akka.actor.setup.DummySetup = DummySetup("Al Dente")
+ val setup2: akka.actor.setup.DummySetup = DummySetup("Earl E. Bird")
+ val setups: akka.actor.setup.ActorSystemSetup = ActorSystemSetup()
.withSetup(setup1)
.withSetup(setup2)
@@ -35,19 +35,19 @@ class ActorSystemSetupSpec extends WordSpec with Matchers {
}
"provide a fluent creation alternative" in {
- val a = DummySetup("Al Dente")
- val b = DummySetup("Earl E. Bird") // same type again
- val c = DummySetup2("Amanda Reckonwith")
- val setups = a and b and c
+ val a: akka.actor.setup.DummySetup = DummySetup("Al Dente")
+ val b: akka.actor.setup.DummySetup = DummySetup("Earl E. Bird") // same type again
+ val c: akka.actor.setup.DummySetup2 = DummySetup2("Amanda Reckonwith")
+ val setups: akka.actor.setup.ActorSystemSetup = a and b and c
setups.get[DummySetup] should ===(Some(b))
setups.get[DummySetup2] should ===(Some(c))
}
"be created with a set of setups" in {
- val setup1 = DummySetup("Manny Kin")
- val setup2 = DummySetup2("Pepe Roni")
- val setups = ActorSystemSetup(setup1, setup2)
+ val setup1: akka.actor.setup.DummySetup = DummySetup("Manny Kin")
+ val setup2: akka.actor.setup.DummySetup2 = DummySetup2("Pepe Roni")
+ val setups: akka.actor.setup.ActorSystemSetup = ActorSystemSetup(setup1, setup2)
setups.get[DummySetup].isDefined shouldBe true
setups.get[DummySetup2].isDefined shouldBe true
@@ -57,7 +57,7 @@ class ActorSystemSetupSpec extends WordSpec with Matchers {
"be available from the ExtendedActorSystem" in {
var system: ActorSystem = null
try {
- val setup = DummySetup("Tad Moore")
+ val setup: akka.actor.setup.DummySetup = DummySetup("Tad Moore")
system = ActorSystem("name", ActorSystemSetup(setup))
system
diff --git a/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala b/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala
index e513135..afebb42 100644
--- a/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/config/ConfigSpec.scala
@@ -20,8 +20,8 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
"The default configuration file (i.e. reference.conf)" must {
"contain all configuration properties for akka-actor that are used in code with their correct defaults" in {
- val settings = system.settings
- val config = settings.config
+ val settings: akka.actor.ActorSystem.Settings = system.settings
+ val config: com.typesafe.config.Config = settings.config
{
import config._
@@ -69,7 +69,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
}
{
- val c = config.getConfig("akka.actor.default-dispatcher")
+ val c: com.typesafe.config.Config = config.getConfig("akka.actor.default-dispatcher")
//General dispatcher config
@@ -84,14 +84,14 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
//Default executor config
{
- val pool = c.getConfig("default-executor")
+ val pool: com.typesafe.config.Config = c.getConfig("default-executor")
pool.getString("fallback") should ===("fork-join-executor")
}
//Fork join executor config
{
- val pool = c.getConfig("fork-join-executor")
+ val pool: com.typesafe.config.Config = c.getConfig("fork-join-executor")
pool.getInt("parallelism-min") should ===(8)
pool.getDouble("parallelism-factor") should ===(3.0)
pool.getInt("parallelism-max") should ===(64)
@@ -101,7 +101,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
//Thread pool executor config
{
- val pool = c.getConfig("thread-pool-executor")
+ val pool: com.typesafe.config.Config = c.getConfig("thread-pool-executor")
import pool._
getDuration("keep-alive-time", TimeUnit.MILLISECONDS) should ===(60 * 1000)
getDouble("core-pool-size-factor") should ===(3.0)
@@ -114,7 +114,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
// Debug config
{
- val debug = config.getConfig("akka.actor.debug")
+ val debug: com.typesafe.config.Config = config.getConfig("akka.actor.debug")
import debug._
getBoolean("receive") should ===(false)
settings.AddLoggingReceive should ===(false)
@@ -141,7 +141,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
}
{
- val c = config.getConfig("akka.actor.default-mailbox")
+ val c: com.typesafe.config.Config = config.getConfig("akka.actor.default-mailbox")
// general mailbox config
diff --git a/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala b/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala
index 122c111..35bf605 100644
--- a/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala
+++ b/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala
@@ -14,7 +14,7 @@ import akka.pattern.{ ask, pipe }
import scala.concurrent.ExecutionException
class Future2ActorSpec extends AkkaSpec with DefaultTimeout {
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
"The Future2Actor bridge" must {
"support convenient sending to multiple destinations" in {
@@ -23,22 +23,22 @@ class Future2ActorSpec extends AkkaSpec with DefaultTimeout {
}
"support convenient sending to multiple destinations with implicit sender" in {
- implicit val someActor = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior }))
+ implicit val someActor: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior }))
Future(42) pipeTo testActor pipeTo testActor
expectMsgAllOf(1 second, 42, 42)
lastSender should ===(someActor)
}
"support convenient sending with explicit sender" in {
- val someActor = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior }))
+ val someActor: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior }))
Future(42).to(testActor, someActor)
expectMsgAllOf(1 second, 42)
lastSender should ===(someActor)
}
"support reply via sender" in {
- val actor = system.actorOf(Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "do" ⇒ Future(31) pipeTo context.sender()
case "ex" ⇒ Future(throw new AssertionError) pipeTo context.sender()
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala
index dcaeffa..010eb15 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala
@@ -31,24 +31,24 @@ class ControlAwareDispatcherSpec extends AkkaSpec(ControlAwareDispatcherSpec.con
}
}
- def testControl(dispatcherKey: String) = {
+ def testControl(dispatcherKey: String): String = {
// It's important that the actor under test is not a top level actor
// with RepointableActorRef, since messages might be queued in
// UnstartedCell and the sent to the PriorityQueue and consumed immediately
// without the ordering taking place.
- val actor = system.actorOf(Props(new Actor {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.actorOf(Props(new Actor {
self ! "test"
self ! "test2"
self ! ImportantMessage
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x ⇒ testActor ! x
}
}).withDispatcher(dispatcherKey))
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}))
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherShutdownSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherShutdownSpec.scala
index 7f813a3..bda7c12 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherShutdownSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/DispatcherShutdownSpec.scala
@@ -17,14 +17,14 @@ class DispatcherShutdownSpec extends WordSpec with Matchers {
"eventualy shutdown when used after system terminate" in {
- val threads = ManagementFactory.getThreadMXBean()
- def threadCount = threads
+ val threads: java.lang.management.ThreadMXBean = ManagementFactory.getThreadMXBean()
+ def threadCount: Int = threads
.dumpAllThreads(false, false).toList
.map(_.getThreadName)
.filter(_.startsWith("DispatcherShutdownSpec-akka.actor.default"))
.size
- val system = ActorSystem("DispatcherShutdownSpec")
+ val system: akka.actor.ActorSystem = ActorSystem("DispatcherShutdownSpec")
threadCount should be > 0
Await.ready(system.terminate(), 1.second)
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala
index 9f7fc07..74b1fd3 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala
@@ -17,7 +17,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
"An ExecutionContext" must {
"be instantiable" in {
- val es = Executors.newCachedThreadPool()
+ val es: java.util.concurrent.ExecutorService = Executors.newCachedThreadPool()
try {
val executor: Executor with ExecutionContext = ExecutionContext.fromExecutor(es)
executor should not be (null)
@@ -45,7 +45,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
override def run: Unit = f
})
- val p = Promise[Unit]()
+ val p: scala.concurrent.Promise[Unit] = Promise[Unit]()
batchable {
val lock, callingThreadLock, count = new AtomicInteger(0)
callingThreadLock.compareAndSet(0, 1) // Enable the lock
@@ -72,11 +72,11 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
override def run: Unit = f
})
- val latch = TestLatch(101)
+ val latch: akka.testkit.TestLatch = TestLatch(101)
batchable {
(1 to 100) foreach { i ⇒
batchable {
- val deadlock = TestLatch(1)
+ val deadlock: akka.testkit.TestLatch = TestLatch(1)
batchable { deadlock.open() }
Await.ready(deadlock, timeout.duration)
latch.countDown()
@@ -91,12 +91,12 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
system.dispatcher.isInstanceOf[BatchingExecutor] should be(true)
import system.dispatcher
- val f = Future(()).flatMap { _ ⇒
+ val f: scala.concurrent.Future[Unit] = Future(()).flatMap { _ ⇒
// this needs to be within an OnCompleteRunnable so that things are added to the batch
- val p = Future.successful(42)
+ val p: scala.concurrent.Future[Int] = Future.successful(42)
// we need the callback list to be non-empty when the blocking{} call is executing
p.onComplete { _ ⇒ () }
- val r = p.map { _ ⇒
+ val r: scala.concurrent.Future[Unit] = p.map { _ ⇒
// trigger the resubmitUnbatched() call
blocking { () }
// make sure that the other task runs to completion before continuing
@@ -114,7 +114,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
system.dispatcher.isInstanceOf[BatchingExecutor] should be(true)
import system.dispatcher
- val f = Future(()).flatMap { _ ⇒
+ val f: scala.concurrent.Future[Int] = Future(()).flatMap { _ ⇒
blocking {
blocking {
blocking {
@@ -127,12 +127,12 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
}
"work with same-thread executor plus blocking" in {
- val ec = akka.dispatch.ExecutionContexts.sameThreadExecutionContext
+ val ec: akka.dispatch.ExecutionContexts.sameThreadExecutionContext.type = akka.dispatch.ExecutionContexts.sameThreadExecutionContext
var x = 0
ec.execute(new Runnable {
- override def run = {
+ override def run: Unit = {
ec.execute(new Runnable {
- override def run = blocking {
+ override def run: Unit = blocking {
x = 1
}
})
@@ -142,20 +142,20 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
}
"work with same-thread dispatcher plus blocking" in {
- val a = TestActorRef(Props(new Actor {
- def receive = {
+ val a: akka.testkit.TestActorRef[Nothing] = TestActorRef(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒
blocking {
sender() ! msg
}
}
}))
- val b = TestActorRef(Props(new Actor {
- def receive = {
+ val b: akka.testkit.TestActorRef[Nothing] = TestActorRef(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ a forward msg
}
}))
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
p.send(b, "hello")
p.expectMsg(0.seconds, "hello")
}
@@ -164,13 +164,13 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
abstract class RunBatch extends Runnable with Batchable {
override def isBatchable = true
}
- val ec = system.dispatchers.lookup(CallingThreadDispatcher.Id)
+ val ec: akka.dispatch.MessageDispatcher = system.dispatchers.lookup(CallingThreadDispatcher.Id)
var x = 0
ec.execute(new RunBatch {
- override def run = {
+ override def run: Unit = {
// enqueue a task to the batch
ec.execute(new RunBatch {
- override def run = blocking {
+ override def run: Unit = blocking {
x = 1
}
})
@@ -186,9 +186,9 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
"A SerializedSuspendableExecutionContext" must {
"be suspendable and resumable" in {
- val sec = SerializedSuspendableExecutionContext(1)(ExecutionContext.global)
- val counter = new AtomicInteger(0)
- def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) }
+ val sec: akka.util.SerializedSuspendableExecutionContext = SerializedSuspendableExecutionContext(1)(ExecutionContext.global)
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ def perform(f: Int ⇒ Int): Unit = sec execute new Runnable { def run: Unit = counter.set(f(counter.get)) }
perform(_ + 1)
perform(x ⇒ { sec.suspend(); x * 2 })
awaitCond(counter.get == 2)
@@ -206,16 +206,16 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
}
"execute 'throughput' number of tasks per sweep" in {
- val submissions = new AtomicInteger(0)
- val counter = new AtomicInteger(0)
- val underlying = new ExecutionContext {
+ val submissions: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val underlying: scala.concurrent.ExecutionContext = new ExecutionContext {
override def execute(r: Runnable) { submissions.incrementAndGet(); ExecutionContext.global.execute(r) }
override def reportFailure(t: Throwable) { ExecutionContext.global.reportFailure(t) }
}
val throughput = 25
- val sec = SerializedSuspendableExecutionContext(throughput)(underlying)
+ val sec: akka.util.SerializedSuspendableExecutionContext = SerializedSuspendableExecutionContext(throughput)(underlying)
sec.suspend()
- def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) }
+ def perform(f: Int ⇒ Int): Unit = sec execute new Runnable { def run: Unit = counter.set(f(counter.get)) }
val total = 1000
1 to total foreach { _ ⇒ perform(_ + 1) }
@@ -227,10 +227,10 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
}
"execute tasks in serial" in {
- val sec = SerializedSuspendableExecutionContext(1)(ExecutionContext.global)
+ val sec: akka.util.SerializedSuspendableExecutionContext = SerializedSuspendableExecutionContext(1)(ExecutionContext.global)
val total = 10000
- val counter = new AtomicInteger(0)
- def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) }
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ def perform(f: Int ⇒ Int): Unit = sec execute new Runnable { def run: Unit = counter.set(f(counter.get)) }
1 to total foreach { i ⇒ perform(c ⇒ if (c == (i - 1)) c + 1 else c) }
awaitCond(counter.get == total)
@@ -238,16 +238,16 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
}
"relinquish thread when suspended" in {
- val submissions = new AtomicInteger(0)
- val counter = new AtomicInteger(0)
- val underlying = new ExecutionContext {
+ val submissions: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(0)
+ val underlying: scala.concurrent.ExecutionContext = new ExecutionContext {
override def execute(r: Runnable) { submissions.incrementAndGet(); ExecutionContext.global.execute(r) }
override def reportFailure(t: Throwable) { ExecutionContext.global.reportFailure(t) }
}
val throughput = 25
- val sec = SerializedSuspendableExecutionContext(throughput)(underlying)
+ val sec: akka.util.SerializedSuspendableExecutionContext = SerializedSuspendableExecutionContext(throughput)(underlying)
sec.suspend()
- def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) }
+ def perform(f: Int ⇒ Int): Unit = sec execute new Runnable { def run: Unit = counter.set(f(counter.get)) }
perform(_ + 1)
1 to 10 foreach { _ ⇒ perform(identity) }
perform(x ⇒ { sec.suspend(); x * 2 })
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala
index 0299328..de06f2c 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala
@@ -5,7 +5,7 @@ import akka.testkit.{ ImplicitSender, AkkaSpec }
import com.typesafe.config.ConfigFactory
object ForkJoinPoolStarvationSpec {
- val config = ConfigFactory.parseString(
+ val config: com.typesafe.config.Config = ConfigFactory.parseString(
"""
|actorhang {
|
@@ -24,7 +24,7 @@ object ForkJoinPoolStarvationSpec {
class SelfBusyActor extends Actor {
self ! "tick"
- override def receive = {
+ override def receive: PartialFunction[Any, Unit] = {
case "tick" ⇒
self ! "tick"
}
@@ -32,7 +32,7 @@ object ForkJoinPoolStarvationSpec {
class InnocentActor extends Actor {
- override def receive = {
+ override def receive: PartialFunction[Any, Unit] = {
case "ping" ⇒
sender ! "All fine"
}
@@ -53,7 +53,7 @@ class ForkJoinPoolStarvationSpec extends AkkaSpec(ForkJoinPoolStarvationSpec.con
system.actorOf(Props(new SelfBusyActor).withDispatcher("actorhang.task-dispatcher"))
system.actorOf(Props(new SelfBusyActor).withDispatcher("actorhang.task-dispatcher"))
- val innocentActor = system.actorOf(Props(new InnocentActor).withDispatcher("actorhang.task-dispatcher"))
+ val innocentActor: akka.actor.ActorRef = system.actorOf(Props(new InnocentActor).withDispatcher("actorhang.task-dispatcher"))
for (_ ← 1 to Iterations) {
// External task submission via the default dispatcher
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala
index a604ace..b1e8eff 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/FutureSpec.scala
@@ -31,7 +31,7 @@ object FutureSpec {
}
class TestActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "Hello" ⇒ sender() ! "World"
case "Failure" ⇒
sender() ! Status.Failure(new RuntimeException("Expected exception; to test fault-tolerance"))
@@ -40,7 +40,7 @@ object FutureSpec {
}
class TestDelayActor(await: TestLatch) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "Hello" ⇒
FutureSpec.ready(await, TestLatch.DefaultTimeout); sender() ! "World"
case "NoReply" ⇒ FutureSpec.ready(await, TestLatch.DefaultTimeout)
@@ -54,10 +54,10 @@ object FutureSpec {
final case class Res[T](res: T)
sealed trait IntAction { def apply(that: Int): Int }
- final case class IntAdd(n: Int) extends IntAction { def apply(that: Int) = that + n }
- final case class IntSub(n: Int) extends IntAction { def apply(that: Int) = that - n }
- final case class IntMul(n: Int) extends IntAction { def apply(that: Int) = that * n }
- final case class IntDiv(n: Int) extends IntAction { def apply(that: Int) = that / n }
+ final case class IntAdd(n: Int) extends IntAction { def apply(that: Int): Int = that + n }
+ final case class IntSub(n: Int) extends IntAction { def apply(that: Int): Int = that - n }
+ final case class IntMul(n: Int) extends IntAction { def apply(that: Int): Int = that * n }
+ final case class IntDiv(n: Int) extends IntAction { def apply(that: Int): Int = that / n }
sealed trait FutureAction {
def /:(that: Try[Int]): Try[Int]
@@ -84,10 +84,10 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"never completed" must {
behave like emptyFuture(_(Promise().future))
"return supplied value on timeout" in {
- val failure = Promise.failed[String](new RuntimeException("br0ken")).future
- val otherFailure = Promise.failed[String](new RuntimeException("last")).future
- val empty = Promise[String]().future
- val timedOut = Promise.successful[String]("Timedout").future
+ val failure: scala.concurrent.Future[String] = Promise.failed[String](new RuntimeException("br0ken")).future
+ val otherFailure: scala.concurrent.Future[String] = Promise.failed[String](new RuntimeException("last")).future
+ val empty: scala.concurrent.Future[String] = Promise[String]().future
+ val timedOut: scala.concurrent.Future[String] = Promise.successful[String]("Timedout").future
Await.result(failure fallbackTo timedOut, timeout.duration) should ===("Timedout")
Await.result(timedOut fallbackTo empty, timeout.duration) should ===("Timedout")
@@ -99,40 +99,40 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"completed with a result" must {
val result = "test value"
- val future = Promise[String]().complete(Success(result)).future
+ val future: scala.concurrent.Future[String] = Promise[String]().complete(Success(result)).future
behave like futureWithResult(_(future, result))
}
"completed with an exception" must {
val message = "Expected Exception"
- val future = Promise[String]().complete(Failure(new RuntimeException(message))).future
+ val future: scala.concurrent.Future[String] = Promise[String]().complete(Failure(new RuntimeException(message))).future
behave like futureWithException[RuntimeException](_(future, message))
}
"completed with an InterruptedException" must {
val message = "Boxed InterruptedException"
- val future = Promise[String]().complete(Failure(new InterruptedException(message))).future
+ val future: scala.concurrent.Future[String] = Promise[String]().complete(Failure(new InterruptedException(message))).future
behave like futureWithException[RuntimeException](_(future, message))
}
"completed with a NonLocalReturnControl" must {
val result = "test value"
- val future = Promise[String]().complete(Failure(new NonLocalReturnControl[String]("test", result))).future
+ val future: scala.concurrent.Future[String] = Promise[String]().complete(Failure(new NonLocalReturnControl[String]("test", result))).future
behave like futureWithResult(_(future, result))
}
"have different ECs" in {
- def namedCtx(n: String) =
+ def namedCtx(n: String): scala.concurrent.ExecutionContextExecutorService =
ExecutionContext.fromExecutorService(
- Executors.newSingleThreadExecutor(new ThreadFactory { def newThread(r: Runnable) = new Thread(r, n) }))
+ Executors.newSingleThreadExecutor(new ThreadFactory { def newThread(r: Runnable): Thread = new Thread(r, n) }))
- val A = namedCtx("A")
- val B = namedCtx("B")
+ val A: scala.concurrent.ExecutionContextExecutorService = namedCtx("A")
+ val B: scala.concurrent.ExecutionContextExecutorService = namedCtx("B")
// create a promise with ctx A
- val p = Promise[String]()
+ val p: scala.concurrent.Promise[String] = Promise[String]()
// I would expect that any callback from p
// is executed in the context of p
- val result = {
- implicit val ec = A
+ val result: scala.concurrent.Future[String] = {
+ implicit val ec: scala.concurrent.ExecutionContextExecutorService = A
p.future map { _ + Thread.currentThread().getName() }
}
@@ -151,9 +151,9 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"awaiting a result" which {
"is not completed" must {
behave like emptyFuture { test ⇒
- val latch = new TestLatch
+ val latch: akka.testkit.TestLatch = new TestLatch
val result = "test value"
- val future = Future {
+ val future: scala.concurrent.Future[String] = Future {
FutureSpec.ready(latch, TestLatch.DefaultTimeout)
result
}
@@ -164,9 +164,9 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"is completed" must {
behave like futureWithResult { test ⇒
- val latch = new TestLatch
+ val latch: akka.testkit.TestLatch = new TestLatch
val result = "test value"
- val future = Future {
+ val future: scala.concurrent.Future[String] = Future {
FutureSpec.ready(latch, TestLatch.DefaultTimeout)
result
}
@@ -180,8 +180,8 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
filterException[ArithmeticException] {
check({ (future: Future[Int], actions: List[FutureAction]) ⇒
def wrap[T](f: Future[T]): Try[T] = FutureSpec.ready(f, timeout.duration).value.get
- val result = (future /: actions)(_ /: _)
- val expected = (wrap(future) /: actions)(_ /: _)
+ val result: scala.concurrent.Future[Int] = (future /: actions)(_ /: _)
+ val expected: scala.util.Try[Int] = (wrap(future) /: actions)(_ /: _)
((wrap(result), expected) match {
case (Success(a), Success(b)) ⇒ a == b
case (Failure(a), Failure(b)) if a.toString == b.toString ⇒ true
@@ -197,8 +197,8 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"from an Actor" which {
"returns a result" must {
behave like futureWithResult { test ⇒
- val actor = system.actorOf(Props[TestActor])
- val future = actor ? "Hello"
+ val actor: akka.actor.ActorRef = system.actorOf(Props[TestActor])
+ val future: scala.concurrent.Future[Any] = actor ? "Hello"
FutureSpec.ready(future, timeout.duration)
test(future, "World")
system.stop(actor)
@@ -207,8 +207,8 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"throws an exception" must {
behave like futureWithException[RuntimeException] { test ⇒
filterException[RuntimeException] {
- val actor = system.actorOf(Props[TestActor])
- val future = actor ? "Failure"
+ val actor: akka.actor.ActorRef = system.actorOf(Props[TestActor])
+ val future: scala.concurrent.Future[Any] = actor ? "Failure"
FutureSpec.ready(future, timeout.duration)
test(future, "Expected exception; to test fault-tolerance")
system.stop(actor)
@@ -220,9 +220,9 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"using flatMap with an Actor" which {
"will return a result" must {
behave like futureWithResult { test ⇒
- val actor1 = system.actorOf(Props[TestActor])
- val actor2 = system.actorOf(Props(new Actor { def receive = { case s: String ⇒ sender() ! s.toUpperCase } }))
- val future = actor1 ? "Hello" flatMap { case s: String ⇒ actor2 ? s }
+ val actor1: akka.actor.ActorRef = system.actorOf(Props[TestActor])
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case s: String ⇒ sender() ! s.toUpperCase } }))
+ val future: scala.concurrent.Future[Any] = actor1 ? "Hello" flatMap { case s: String ⇒ actor2 ? s }
FutureSpec.ready(future, timeout.duration)
test(future, "WORLD")
system.stop(actor1)
@@ -232,9 +232,9 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"will throw an exception" must {
behave like futureWithException[ArithmeticException] { test ⇒
filterException[ArithmeticException] {
- val actor1 = system.actorOf(Props[TestActor])
- val actor2 = system.actorOf(Props(new Actor { def receive = { case s: String ⇒ sender() ! Status.Failure(new ArithmeticException("/ by zero")) } }))
- val future = actor1 ? "Hello" flatMap { case s: String ⇒ actor2 ? s }
+ val actor1: akka.actor.ActorRef = system.actorOf(Props[TestActor])
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case s: String ⇒ sender() ! Status.Failure(new ArithmeticException("/ by zero")) } }))
+ val future: scala.concurrent.Future[Any] = actor1 ? "Hello" flatMap { case s: String ⇒ actor2 ? s }
FutureSpec.ready(future, timeout.duration)
test(future, "/ by zero")
system.stop(actor1)
@@ -245,9 +245,9 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"will throw a NoSuchElementException when matching wrong type" must {
behave like futureWithException[NoSuchElementException] { test ⇒
filterException[NoSuchElementException] {
- val actor1 = system.actorOf(Props[TestActor])
- val actor2 = system.actorOf(Props(new Actor { def receive = { case s: String ⇒ sender() ! s.toUpperCase } }))
- val future = actor1 ? "Hello" flatMap { case i: Int ⇒ actor2 ? i }
+ val actor1: akka.actor.ActorRef = system.actorOf(Props[TestActor])
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case s: String ⇒ sender() ! s.toUpperCase } }))
+ val future: scala.concurrent.Future[Any] = actor1 ? "Hello" flatMap { case i: Int ⇒ actor2 ? i }
FutureSpec.ready(future, timeout.duration)
test(future, "World (of class java.lang.String)")
system.stop(actor1)
@@ -261,22 +261,22 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"compose with for-comprehensions" in {
filterException[ClassCastException] {
- val actor = system.actorOf(Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case s: String ⇒ sender() ! s.length
case i: Int ⇒ sender() ! (i * 2).toString
}
}))
- val future0 = actor ? "Hello"
+ val future0: scala.concurrent.Future[Any] = actor ? "Hello"
- val future1 = for {
+ val future1: scala.concurrent.Future[String] = for {
a ← future0.mapTo[Int] // returns 5
b ← (actor ? a).mapTo[String] // returns "10"
c ← (actor ? 7).mapTo[String] // returns "14"
} yield b + "-" + c
- val future2 = for {
+ val future2: scala.concurrent.Future[String] = for {
a ← future0.mapTo[Int]
b ← (actor ? a).mapTo[Int]
c ← (actor ? 7).mapTo[String]
@@ -291,20 +291,20 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"support pattern matching within a for-comprehension" in {
filterException[NoSuchElementException] {
- val actor = system.actorOf(Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Req(s: String) ⇒ sender() ! Res(s.length)
case Req(i: Int) ⇒ sender() ! Res((i * 2).toString)
}
}))
- val future1 = for {
+ val future1: scala.concurrent.Future[String] = for {
Res(a: Int) ← actor ? Req("Hello")
Res(b: String) ← actor ? Req(a)
Res(c: String) ← actor ? Req(7)
} yield b + "-" + c
- val future2 = for {
+ val future2: scala.concurrent.Future[String] = for {
Res(a: Int) ← actor ? Req("Hello")
Res(b: Int) ← actor ? Req(a)
Res(c: Int) ← actor ? Req(7)
@@ -318,34 +318,34 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"recover from exceptions" in {
filterException[RuntimeException] {
- val future1 = Future(5)
- val future2 = future1 map (_ / 0)
- val future3 = future2 map (_.toString)
+ val future1: scala.concurrent.Future[Int] = Future(5)
+ val future2: scala.concurrent.Future[Int] = future1 map (_ / 0)
+ val future3: scala.concurrent.Future[String] = future2 map (_.toString)
- val future4 = future1 recover {
+ val future4: scala.concurrent.Future[String] = future1 recover {
case e: ArithmeticException ⇒ 0
} map (_.toString)
- val future5 = future2 recover {
+ val future5: scala.concurrent.Future[String] = future2 recover {
case e: ArithmeticException ⇒ 0
} map (_.toString)
- val future6 = future2 recover {
+ val future6: scala.concurrent.Future[String] = future2 recover {
case e: MatchError ⇒ 0
} map (_.toString)
- val future7 = future3 recover { case e: ArithmeticException ⇒ "You got ERROR" }
+ val future7: scala.concurrent.Future[String] = future3 recover { case e: ArithmeticException ⇒ "You got ERROR" }
- val actor = system.actorOf(Props[TestActor])
+ val actor: akka.actor.ActorRef = system.actorOf(Props[TestActor])
- val future8 = actor ? "Failure"
- val future9 = actor ? "Failure" recover {
+ val future8: scala.concurrent.Future[Any] = actor ? "Failure"
+ val future9: scala.concurrent.Future[Any] = actor ? "Failure" recover {
case e: RuntimeException ⇒ "FAIL!"
}
- val future10 = actor ? "Hello" recover {
+ val future10: scala.concurrent.Future[Any] = actor ? "Hello" recover {
case e: RuntimeException ⇒ "FAIL!"
}
- val future11 = actor ? "Failure" recover { case _ ⇒ "Oops!" }
+ val future11: scala.concurrent.Future[Any] = actor ? "Failure" recover { case _ ⇒ "Oops!" }
Await.result(future1, timeout.duration) should ===(5)
intercept[ArithmeticException] { Await.result(future2, timeout.duration) }
@@ -364,9 +364,9 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"recoverWith from exceptions" in {
- val o = new IllegalStateException("original")
- val r = new IllegalStateException("recovered")
- val yay = Promise.successful("yay!").future
+ val o: IllegalStateException = new IllegalStateException("original")
+ val r: IllegalStateException = new IllegalStateException("recovered")
+ val yay: scala.concurrent.Future[String] = Promise.successful("yay!").future
intercept[IllegalStateException] {
Await.result(Promise.failed[String](o).future recoverWith { case _ if false == true ⇒ yay }, timeout.duration)
@@ -380,7 +380,7 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"andThen like a boss" in {
- val q = new LinkedBlockingQueue[Int]
+ val q: java.util.concurrent.LinkedBlockingQueue[Int] = new LinkedBlockingQueue[Int]
for (i ← 1 to 1000) {
Await.result(Future { q.add(1); 3 } andThen { case _ ⇒ q.add(2) } andThen { case Success(0) ⇒ q.add(Int.MaxValue) } andThen { case _ ⇒ q.add(3); }, timeout.duration) should ===(3)
q.poll() should ===(1)
@@ -391,16 +391,16 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"firstCompletedOf" in {
- val futures = Vector.fill[Future[Int]](10)(Promise[Int]().future) :+ Promise.successful[Int](5).future
+ val futures: scala.collection.immutable.Vector[scala.concurrent.Future[Int]] = Vector.fill[Future[Int]](10)(Promise[Int]().future) :+ Promise.successful[Int](5).future
Await.result(Future.firstCompletedOf(futures), timeout.duration) should ===(5)
}
"find" in {
- val futures = for (i ← 1 to 10) yield Future { i }
- val result = Future.find[Int](futures)(_ == 3)
+ val futures: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[Int]] = for (i ← 1 to 10) yield Future { i }
+ val result: scala.concurrent.Future[Option[Int]] = Future.find[Int](futures)(_ == 3)
Await.result(result, timeout.duration) should ===(Some(3))
- val notFound = Future.find[Int](futures)(_ == 11)
+ val notFound: scala.concurrent.Future[Option[Int]] = Future.find[Int](futures)(_ == 11)
Await.result(notFound, timeout.duration) should ===(None)
}
@@ -409,8 +409,8 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"zip" in {
- val timeout = 10000 millis
- val f = new IllegalStateException("test")
+ val timeout: scala.concurrent.duration.FiniteDuration = 10000 millis
+ val f: IllegalStateException = new IllegalStateException("test")
intercept[IllegalStateException] {
Await.result(Promise.failed[String](f).future zip Promise.successful("foo").future, timeout)
} should ===(f)
@@ -427,13 +427,13 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"fold by composing" in {
- val futures = (1 to 10).toList map { i ⇒ Future(i) }
+ val futures: List[scala.concurrent.Future[Int]] = (1 to 10).toList map { i ⇒ Future(i) }
Await.result(futures.foldLeft(Future(0))((fr, fa) ⇒ for (r ← fr; a ← fa) yield (r + a)), timeout.duration) should ===(55)
}
"fold with an exception" in {
filterException[IllegalArgumentException] {
- val futures = (1 to 10).toList map {
+ val futures: List[scala.concurrent.Future[Int]] = (1 to 10).toList map {
case 6 ⇒ Future(throw new IllegalArgumentException("shouldFoldResultsWithException: expected"))
case i ⇒ Future(i)
}
@@ -444,12 +444,12 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"fold mutable zeroes safely" in {
import scala.collection.mutable.ArrayBuffer
def test(testNumber: Int) {
- val fs = (0 to 1000) map (i ⇒ Future(i))
- val f = compat.Future.fold(fs)(ArrayBuffer.empty[AnyRef]) {
+ val fs: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[Int]] = (0 to 1000) map (i ⇒ Future(i))
+ val f: scala.concurrent.Future[scala.collection.mutable.ArrayBuffer[AnyRef]] = compat.Future.fold(fs)(ArrayBuffer.empty[AnyRef]) {
case (l, i) if i % 2 == 0 ⇒ l += i.asInstanceOf[AnyRef]
case (l, _) ⇒ l
}
- val result = Await.result(f.mapTo[ArrayBuffer[Int]], 10000 millis).sum
+ val result: Int = Await.result(f.mapTo[ArrayBuffer[Int]], 10000 millis).sum
assert(result === 250500)
}
@@ -462,13 +462,13 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"reduce results" in {
- val futures = (1 to 10).toList map { i ⇒ Future(i) }
+ val futures: List[scala.concurrent.Future[Int]] = (1 to 10).toList map { i ⇒ Future(i) }
assert(Await.result(compat.Future.reduce(futures)(_ + _), remainingOrDefault) === 55)
}
"reduce results with Exception" in {
filterException[IllegalArgumentException] {
- val futures = (1 to 10).toList map {
+ val futures: List[scala.concurrent.Future[Int]] = (1 to 10).toList map {
case 6 ⇒ Future(throw new IllegalArgumentException("shouldReduceResultsWithException: expected"))
case i ⇒ Future(i)
}
@@ -483,29 +483,29 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"execute foreach when received ask reply" in {
- val latch = new TestLatch
- val actor = system.actorOf(Props[TestActor])
+ val latch: akka.testkit.TestLatch = new TestLatch
+ val actor: akka.actor.ActorRef = system.actorOf(Props[TestActor])
actor ? "Hello" foreach { case "World" ⇒ latch.open() }
FutureSpec.ready(latch, 5 seconds)
system.stop(actor)
}
"traverse Futures" in {
- val oddActor = system.actorOf(Props(new Actor {
+ val oddActor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
var counter = 1
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case 'GetNext ⇒
sender() ! counter
counter += 2
}
}))
- val oddFutures = List.fill(100)(oddActor ? 'GetNext mapTo classTag[Int])
+ val oddFutures: List[scala.concurrent.Future[Int]] = List.fill(100)(oddActor ? 'GetNext mapTo classTag[Int])
assert(Await.result(Future.sequence(oddFutures), timeout.duration).sum === 10000)
system.stop(oddActor)
- val list = (1 to 100).toList
+ val list: List[Int] = (1 to 100).toList
assert(Await.result(Future.traverse(list)(x ⇒ Future(x * 2 - 1)), timeout.duration).sum === 10000)
}
@@ -513,14 +513,14 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
class ThrowableTest(m: String) extends Throwable(m)
EventFilter[ThrowableTest](occurrences = 4) intercept {
- val f1 = Future[Any] { throw new ThrowableTest("test") }
+ val f1: scala.concurrent.Future[Any] = Future[Any] { throw new ThrowableTest("test") }
intercept[ThrowableTest] { Await.result(f1, timeout.duration) }
- val latch = new TestLatch
- val f2 = Future { FutureSpec.ready(latch, 5 seconds); "success" }
+ val latch: akka.testkit.TestLatch = new TestLatch
+ val f2: scala.concurrent.Future[String] = Future { FutureSpec.ready(latch, 5 seconds); "success" }
f2 foreach (_ ⇒ throw new ThrowableTest("dispatcher foreach"))
f2 foreach { _ ⇒ throw new ThrowableTest("dispatcher receive") }
- val f3 = f2 map (s ⇒ s.toUpperCase)
+ val f3: scala.concurrent.Future[String] = f2 map (s ⇒ s.toUpperCase)
latch.open()
assert(Await.result(f2, timeout.duration) === "success")
f2 foreach (_ ⇒ throw new ThrowableTest("current thread foreach"))
@@ -530,24 +530,24 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"block until result" in {
- val latch = new TestLatch
+ val latch: akka.testkit.TestLatch = new TestLatch
- val f = Future { FutureSpec.ready(latch, 5 seconds); 5 }
- val f2 = Future { Await.result(f, timeout.duration) + 5 }
+ val f: scala.concurrent.Future[Int] = Future { FutureSpec.ready(latch, 5 seconds); 5 }
+ val f2: scala.concurrent.Future[Int] = Future { Await.result(f, timeout.duration) + 5 }
intercept[TimeoutException](FutureSpec.ready(f2, 100 millis))
latch.open()
assert(Await.result(f2, timeout.duration) === 10)
- val f3 = Promise[Int]().future
+ val f3: scala.concurrent.Future[Int] = Promise[Int]().future
filterException[TimeoutException] { intercept[TimeoutException] { FutureSpec.ready(f3, 0 millis) } }
}
"run callbacks async" in {
- val latch = Vector.fill(10)(new TestLatch)
+ val latch: scala.collection.immutable.Vector[akka.testkit.TestLatch] = Vector.fill(10)(new TestLatch)
- val f1 = Future { latch(0).open(); FutureSpec.ready(latch(1), TestLatch.DefaultTimeout); "Hello" }
- val f2 = f1 map { s ⇒ latch(2).open(); FutureSpec.ready(latch(3), TestLatch.DefaultTimeout); s.length }
+ val f1: scala.concurrent.Future[String] = Future { latch(0).open(); FutureSpec.ready(latch(1), TestLatch.DefaultTimeout); "Hello" }
+ val f2: scala.concurrent.Future[Int] = f1 map { s ⇒ latch(2).open(); FutureSpec.ready(latch(3), TestLatch.DefaultTimeout); s.length }
f2 foreach (_ ⇒ latch(4).open())
FutureSpec.ready(latch(0), TestLatch.DefaultTimeout)
@@ -561,7 +561,7 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
f1 should be('completed)
f2 should not be ('completed)
- val f3 = f1 map { s ⇒ latch(5).open(); FutureSpec.ready(latch(6), TestLatch.DefaultTimeout); s.length * 2 }
+ val f3: scala.concurrent.Future[Int] = f1 map { s ⇒ latch(5).open(); FutureSpec.ready(latch(6), TestLatch.DefaultTimeout); s.length * 2 }
f3 foreach (_ ⇒ latch(3).open())
FutureSpec.ready(latch(5), TestLatch.DefaultTimeout)
@@ -574,8 +574,8 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
f2 should be('completed)
f3 should be('completed)
- val p1 = Promise[String]()
- val f4 = p1.future map { s ⇒ latch(7).open(); FutureSpec.ready(latch(8), TestLatch.DefaultTimeout); s.length }
+ val p1: scala.concurrent.Promise[String] = Promise[String]()
+ val f4: scala.concurrent.Future[Int] = p1.future map { s ⇒ latch(7).open(); FutureSpec.ready(latch(8), TestLatch.DefaultTimeout); s.length }
f4 foreach (_ ⇒ latch(9).open())
p1 should not be ('completed)
@@ -595,12 +595,12 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"not deadlock with nested await (ticket 1313)" in {
- val simple = Future(()) map (_ ⇒ Await.result((Future(()) map (_ ⇒ ())), timeout.duration))
+ val simple: scala.concurrent.Future[Unit] = Future(()) map (_ ⇒ Await.result((Future(()) map (_ ⇒ ())), timeout.duration))
FutureSpec.ready(simple, timeout.duration) should be('completed)
val l1, l2 = new TestLatch
- val complex = Future(()) map { _ ⇒
- val nested = Future(())
+ val complex: scala.concurrent.Future[akka.testkit.TestLatch] = Future(()) map { _ ⇒
+ val nested: scala.concurrent.Future[Unit] = Future(())
nested foreach (_ ⇒ l1.open())
FutureSpec.ready(l1, TestLatch.DefaultTimeout) // make sure nested is completed
nested foreach (_ ⇒ l2.open())
@@ -610,11 +610,11 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
}
"re-use the same thread for nested futures with batching ExecutionContext" in {
- val failCount = new java.util.concurrent.atomic.AtomicInteger
- val f = Future(()) flatMap { _ ⇒
- val originalThread = Thread.currentThread
+ val failCount: java.util.concurrent.atomic.AtomicInteger = new java.util.concurrent.atomic.AtomicInteger
+ val f: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[AnyVal]] = Future(()) flatMap { _ ⇒
+ val originalThread: Thread = Thread.currentThread
// run some nested futures
- val nested =
+ val nested: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[AnyVal]] =
for (i ← 1 to 100)
yield Future.successful("abc") flatMap { _ ⇒
if (Thread.currentThread ne originalThread)
@@ -655,13 +655,13 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"transform result with map" in { f((future, result) ⇒ Await.result((future map (_.toString.length)), timeout.duration) should ===(result.toString.length)) }
"compose result with flatMap" in {
f { (future, result) ⇒
- val r = for (r ← future; p ← Promise.successful("foo").future) yield r.toString + p
+ val r: scala.concurrent.Future[String] = for (r ← future; p ← Promise.successful("foo").future) yield r.toString + p
Await.result(r, timeout.duration) should ===(result.toString + "foo")
}
}
"perform action with foreach" in {
f { (future, result) ⇒
- val p = Promise[Any]()
+ val p: scala.concurrent.Promise[Any] = Promise[Any]()
future foreach p.success
Await.result(p.future, timeout.duration) should ===(result)
}
@@ -675,7 +675,7 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"not recover from exception" in { f((future, result) ⇒ Await.result(future.recover({ case _ ⇒ "pigdog" }), timeout.duration) should ===(result)) }
"perform action on result" in {
f { (future, result) ⇒
- val p = Promise[Any]()
+ val p: scala.concurrent.Promise[Any] = Promise[Any]()
future.foreach { x ⇒ p.success(x) }
Await.result(p.future, timeout.duration) should ===(result)
}
@@ -715,14 +715,14 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"project a failure" in { f((future, message) ⇒ Await.result(future.failed, timeout.duration).getMessage should ===(message)) }
"perform action on exception" in {
f { (future, message) ⇒
- val p = Promise[Any]()
+ val p: scala.concurrent.Promise[Any] = Promise[Any]()
future.failed.foreach { _ ⇒ p.success(message) }
Await.result(p.future, timeout.duration) should ===(message)
}
}
"always cast successfully using mapTo" in {
f((future, message) ⇒ {
- val exception = the[java.lang.Exception] thrownBy {
+ val exception: Exception = the[java.lang.Exception] thrownBy {
Await.result(future.mapTo[java.lang.Thread], timeout.duration)
}
exception.getMessage should ===(message)
@@ -734,14 +734,14 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
implicit def arbFutureAction: Arbitrary[FutureAction] = Arbitrary {
- val genIntAction = for {
+ val genIntAction: org.scalacheck.Gen[Product with Serializable with akka.dispatch.FutureSpec.IntAction] = for {
n ← arbitrary[Int]
a ← Gen.oneOf(IntAdd(n), IntSub(n), IntMul(n), IntDiv(n))
} yield a
- val genMapAction = genIntAction map (MapAction(_))
+ val genMapAction: org.scalacheck.Gen[akka.dispatch.FutureSpec.MapAction] = genIntAction map (MapAction(_))
- val genFlatMapAction = genIntAction map (FlatMapAction(_))
+ val genFlatMapAction: org.scalacheck.Gen[akka.dispatch.FutureSpec.FlatMapAction] = genIntAction map (FlatMapAction(_))
Gen.oneOf(genMapAction, genFlatMapAction)
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala
index 8a59ff1..72ab538 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala
@@ -27,8 +27,8 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
name should {
"create an unbounded mailbox" in {
- val config = UnboundedMailbox()
- val q = factory(config)
+ val config: akka.dispatch.UnboundedMailbox = UnboundedMailbox()
+ val q: akka.dispatch.MessageQueue = factory(config)
ensureInitialMailboxState(config, q)
}
@@ -41,9 +41,9 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
}
"create a bounded mailbox with 10 capacity and with push timeout" in {
- val config = BoundedMailbox(10, 10 milliseconds)
+ val config: akka.dispatch.BoundedMailbox = BoundedMailbox(10, 10 milliseconds)
config.capacity should ===(10)
- val q = factory(config)
+ val q: akka.dispatch.MessageQueue = factory(config)
ensureInitialMailboxState(config, q)
for (i ← 1 to config.capacity) q.enqueue(testActor, exampleMessage)
@@ -92,7 +92,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
}
def ensureSingleConsumerEnqueueDequeue(config: MailboxType) {
- val q = factory(config)
+ val q: akka.dispatch.MessageQueue = factory(config)
ensureMailboxSize(q, 0)
q.dequeue should ===(null)
for (i ← 1 to 100) {
@@ -130,7 +130,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
enqueueN: Int = 10000,
dequeueN: Int = 10000,
parallel: Boolean = true): Unit = within(10 seconds) {
- val q = factory(config)
+ val q: akka.dispatch.MessageQueue = factory(config)
ensureInitialMailboxState(config, q)
EventFilter.warning(
@@ -138,14 +138,14 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
occurrences = (enqueueN - dequeueN)) intercept {
def createProducer(fromNum: Int, toNum: Int): Future[Vector[Envelope]] = spawn {
- val messages = Vector() ++ (for (i ← fromNum to toNum) yield createMessageInvocation(i))
+ val messages: scala.collection.immutable.Vector[akka.dispatch.Envelope] = Vector() ++ (for (i ← fromNum to toNum) yield createMessageInvocation(i))
for (i ← messages) q.enqueue(testActor, i)
messages
}
- val producers = {
+ val producers: List[scala.concurrent.Future[Vector[akka.dispatch.Envelope]]] = {
val step = 500
- val ps = for (i ← (1 to enqueueN by step).toList) yield createProducer(i, Math.min(enqueueN, i + step - 1))
+ val ps: List[scala.concurrent.Future[Vector[akka.dispatch.Envelope]]] = for (i ← (1 to enqueueN by step).toList) yield createProducer(i, Math.min(enqueueN, i + step - 1))
if (parallel == false)
ps foreach { Await.ready(_, remainingOrDefault) }
@@ -162,10 +162,10 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
r
}
- val consumers = List.fill(maxConsumers)(createConsumer)
+ val consumers: List[scala.concurrent.Future[Vector[akka.dispatch.Envelope]]] = List.fill(maxConsumers)(createConsumer)
- val ps = producers.map(Await.result(_, remainingOrDefault))
- val cs = consumers.map(Await.result(_, remainingOrDefault))
+ val ps: List[Vector[akka.dispatch.Envelope]] = producers.map(Await.result(_, remainingOrDefault))
+ val cs: List[Vector[akka.dispatch.Envelope]] = consumers.map(Await.result(_, remainingOrDefault))
ps.map(_.size).sum should ===(enqueueN) //Must have produced 1000 messages
cs.map(_.size).sum should ===(dequeueN) //Must have consumed all produced messages
@@ -181,25 +181,25 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
class DefaultMailboxSpec extends MailboxSpec {
lazy val name = "The default mailbox implementation"
- def factory = {
+ def factory: akka.dispatch.MailboxType ⇒ akka.dispatch.MessageQueue = {
case u: UnboundedMailbox ⇒ u.create(None, None)
case b: BoundedMailbox ⇒ b.create(None, None)
}
}
class PriorityMailboxSpec extends MailboxSpec {
- val comparator = PriorityGenerator(_.##)
+ val comparator: akka.dispatch.PriorityGenerator = PriorityGenerator(_.##)
lazy val name = "The priority mailbox implementation"
- def factory = {
+ def factory: akka.dispatch.MailboxType ⇒ akka.dispatch.MessageQueue = {
case UnboundedMailbox() ⇒ new UnboundedPriorityMailbox(comparator).create(None, None)
case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedPriorityMailbox(comparator, capacity, pushTimeOut).create(None, None)
}
}
class StablePriorityMailboxSpec extends MailboxSpec {
- val comparator = PriorityGenerator(_.##)
+ val comparator: akka.dispatch.PriorityGenerator = PriorityGenerator(_.##)
lazy val name = "The stable priority mailbox implementation"
- def factory = {
+ def factory: akka.dispatch.MailboxType ⇒ akka.dispatch.MessageQueue = {
case UnboundedMailbox() ⇒ new UnboundedStablePriorityMailbox(comparator).create(None, None)
case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedStablePriorityMailbox(comparator, capacity, pushTimeOut).create(None, None)
}
@@ -207,7 +207,7 @@ class StablePriorityMailboxSpec extends MailboxSpec {
class ControlAwareMailboxSpec extends MailboxSpec {
lazy val name = "The control aware mailbox implementation"
- def factory = {
+ def factory: akka.dispatch.MailboxType ⇒ akka.dispatch.MessageQueue = {
case UnboundedMailbox() ⇒ new UnboundedControlAwareMailbox().create(None, None)
case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedControlAwareMailbox(capacity, pushTimeOut).create(None, None)
}
@@ -221,26 +221,26 @@ object CustomMailboxSpec {
"""
class MyMailboxType(settings: ActorSystem.Settings, config: Config) extends MailboxType {
- override def create(owner: Option[ActorRef], system: Option[ActorSystem]) = owner match {
+ override def create(owner: Option[ActorRef], system: Option[ActorSystem]): akka.dispatch.MessageQueue = owner match {
case Some(o) ⇒ new MyMailbox(o)
case None ⇒ throw new Exception("no mailbox owner given")
}
}
class MyMailbox(owner: ActorRef) extends UnboundedQueueBasedMessageQueue {
- final val queue = new ConcurrentLinkedQueue[Envelope]()
+ final val queue: java.util.concurrent.ConcurrentLinkedQueue[akka.dispatch.Envelope] = new ConcurrentLinkedQueue[Envelope]()
}
}
class CustomMailboxSpec extends AkkaSpec(CustomMailboxSpec.config) {
"Dispatcher configuration" must {
"support custom mailboxType" in {
- val actor = system.actorOf(Props.empty.withDispatcher("my-dispatcher"))
+ val actor: akka.actor.ActorRef = system.actorOf(Props.empty.withDispatcher("my-dispatcher"))
awaitCond(actor match {
case r: RepointableRef ⇒ r.isStarted
case _ ⇒ true
}, 1 second, 10 millis)
- val queue = actor.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].mailbox.messageQueue
+ val queue: akka.dispatch.MessageQueue = actor.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].mailbox.messageQueue
queue.getClass should ===(classOf[CustomMailboxSpec.MyMailbox])
}
}
@@ -249,7 +249,7 @@ class CustomMailboxSpec extends AkkaSpec(CustomMailboxSpec.config) {
class SingleConsumerOnlyMailboxSpec extends MailboxSpec {
lazy val name = "The single-consumer-only mailbox implementation"
override def maxConsumers = 1
- def factory = {
+ def factory: akka.dispatch.MailboxType ⇒ akka.dispatch.MessageQueue = {
case u: UnboundedMailbox ⇒ SingleConsumerOnlyUnboundedMailbox().create(None, None)
case b @ BoundedMailbox(capacity, _) ⇒ NonBlockingBoundedMailbox(capacity).create(None, None)
}
@@ -257,7 +257,7 @@ class SingleConsumerOnlyMailboxSpec extends MailboxSpec {
object SingleConsumerOnlyMailboxVerificationSpec {
case object Ping
- val mailboxConf = ConfigFactory.parseString("""
+ val mailboxConf: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.actor.serialize-messages = off
test-unbounded-dispatcher {
mailbox-type = "akka.dispatch.SingleConsumerOnlyUnboundedMailbox"
@@ -275,11 +275,11 @@ class SingleConsumerOnlyMailboxVerificationSpec extends AkkaSpec(SingleConsumerO
def pathologicalPingPong(dispatcherId: String): Unit = {
val total = 2000000
- val runner = system.actorOf(Props(new Actor {
+ val runner: akka.actor.ActorRef = system.actorOf(Props(new Actor {
val a, b = context.watch(
context.actorOf(Props(new Actor {
- var n = total / 2
- def receive = {
+ var n: Int = total / 2
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒
n -= 1
sender() ! Ping
@@ -287,7 +287,7 @@ class SingleConsumerOnlyMailboxVerificationSpec extends AkkaSpec(SingleConsumerO
context stop self
}
}).withDispatcher(dispatcherId)))
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Ping ⇒ a.tell(Ping, b)
case Terminated(`a` | `b`) ⇒ if (context.children.isEmpty) context stop self
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala
index 191d6e1..510b032 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala
@@ -45,28 +45,28 @@ class PriorityDispatcherSpec extends AkkaSpec(PriorityDispatcherSpec.config) wit
}
def testOrdering(dispatcherKey: String) {
- val msgs = (1 to 100) toList
+ val msgs: List[Int] = (1 to 100) toList
// It's important that the actor under test is not a top level actor
// with RepointableActorRef, since messages might be queued in
// UnstartedCell and the sent to the PriorityQueue and consumed immediately
// without the ordering taking place.
- val actor = system.actorOf(Props(new Actor {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.actorOf(Props(new Actor {
- val acc = scala.collection.mutable.ListBuffer[Int]()
+ val acc: scala.collection.mutable.ListBuffer[Int] = scala.collection.mutable.ListBuffer[Int]()
scala.util.Random.shuffle(msgs) foreach { m ⇒ self ! m }
self.tell('Result, testActor)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case i: Int ⇒ acc += i
case 'Result ⇒ sender() ! acc.toList
}
}).withDispatcher(dispatcherKey))
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}))
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala
index 03418eb..76b53e0 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala
@@ -51,36 +51,36 @@ class StablePriorityDispatcherSpec extends AkkaSpec(StablePriorityDispatcherSpec
}
def testOrdering(dispatcherKey: String) {
- val msgs = (1 to 200) toList
- val shuffled = scala.util.Random.shuffle(msgs)
+ val msgs: List[Int] = (1 to 200) toList
+ val shuffled: List[Int] = scala.util.Random.shuffle(msgs)
// It's important that the actor under test is not a top level actor
// with RepointableActorRef, since messages might be queued in
// UnstartedCell and then sent to the StablePriorityQueue and consumed immediately
// without the ordering taking place.
- val actor = system.actorOf(Props(new Actor {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
context.actorOf(Props(new Actor {
- val acc = scala.collection.mutable.ListBuffer[Int]()
+ val acc: scala.collection.mutable.ListBuffer[Int] = scala.collection.mutable.ListBuffer[Int]()
shuffled foreach { m ⇒ self ! m }
self.tell('Result, testActor)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case i: Int ⇒ acc += i
case 'Result ⇒ sender() ! acc.toList
}
}).withDispatcher(dispatcherKey))
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}))
// Low messages should come out first, and in priority order. High messages follow - they are equal priority and
// should come out in the same order in which they were sent.
- val lo = (1 to 100) toList
- val hi = shuffled filter { _ > 100 }
+ val lo: List[Int] = (1 to 100) toList
+ val hi: List[Int] = shuffled filter { _ > 100 }
expectMsgType[List[Int]] should ===(lo ++ hi)
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/sysmsg/SystemMessageListSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/sysmsg/SystemMessageListSpec.scala
index 7cdd35c..286df89 100644
--- a/akka-actor-tests/src/test/scala/akka/dispatch/sysmsg/SystemMessageListSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/dispatch/sysmsg/SystemMessageListSpec.scala
@@ -10,7 +10,7 @@ class SystemMessageListSpec extends AkkaSpec {
import SystemMessageList.LNil
import SystemMessageList.ENil
- val child = system.actorOf(Props.empty, "dummy") // need an ActorRef for the Failed msg
+ val child: akka.actor.ActorRef = system.actorOf(Props.empty, "dummy") // need an ActorRef for the Failed msg
"The SystemMessageList value class" must {
@@ -21,9 +21,9 @@ class SystemMessageListSpec extends AkkaSpec {
}
"able to append messages" in {
- val create0 = Failed(child, null, 0)
- val create1 = Failed(child, null, 1)
- val create2 = Failed(child, null, 2)
+ val create0: akka.dispatch.sysmsg.Failed = Failed(child, null, 0)
+ val create1: akka.dispatch.sysmsg.Failed = Failed(child, null, 1)
+ val create2: akka.dispatch.sysmsg.Failed = Failed(child, null, 2)
((create0 :: LNil).head eq create0) should ===(true)
((create1 :: create0 :: LNil).head eq create1) should ===(true)
((create2 :: create1 :: create0 :: LNil).head eq create2) should ===(true)
@@ -34,10 +34,10 @@ class SystemMessageListSpec extends AkkaSpec {
}
"able to deconstruct head and tail" in {
- val create0 = Failed(child, null, 0)
- val create1 = Failed(child, null, 1)
- val create2 = Failed(child, null, 2)
- val list = create2 :: create1 :: create0 :: LNil
+ val create0: akka.dispatch.sysmsg.Failed = Failed(child, null, 0)
+ val create1: akka.dispatch.sysmsg.Failed = Failed(child, null, 1)
+ val create2: akka.dispatch.sysmsg.Failed = Failed(child, null, 2)
+ val list: akka.dispatch.sysmsg.LatestFirstSystemMessageList = create2 :: create1 :: create0 :: LNil
(list.head eq create2) should ===(true)
(list.tail.head eq create1) should ===(true)
@@ -46,10 +46,10 @@ class SystemMessageListSpec extends AkkaSpec {
}
"properly report size and emptyness" in {
- val create0 = Failed(child, null, 0)
- val create1 = Failed(child, null, 1)
- val create2 = Failed(child, null, 2)
- val list = create2 :: create1 :: create0 :: LNil
+ val create0: akka.dispatch.sysmsg.Failed = Failed(child, null, 0)
+ val create1: akka.dispatch.sysmsg.Failed = Failed(child, null, 1)
+ val create2: akka.dispatch.sysmsg.Failed = Failed(child, null, 2)
+ val list: akka.dispatch.sysmsg.LatestFirstSystemMessageList = create2 :: create1 :: create0 :: LNil
list.size should ===(3)
list.isEmpty should ===(false)
@@ -66,10 +66,10 @@ class SystemMessageListSpec extends AkkaSpec {
}
"properly reverse contents" in {
- val create0 = Failed(child, null, 0)
- val create1 = Failed(child, null, 1)
- val create2 = Failed(child, null, 2)
- val list = create2 :: create1 :: create0 :: LNil
+ val create0: akka.dispatch.sysmsg.Failed = Failed(child, null, 0)
+ val create1: akka.dispatch.sysmsg.Failed = Failed(child, null, 1)
+ val create2: akka.dispatch.sysmsg.Failed = Failed(child, null, 2)
+ val list: akka.dispatch.sysmsg.LatestFirstSystemMessageList = create2 :: create1 :: create0 :: LNil
val listRev: EarliestFirstSystemMessageList = list.reverse
listRev.isEmpty should ===(false)
@@ -90,17 +90,17 @@ class SystemMessageListSpec extends AkkaSpec {
"EarliestFirstSystemMessageList" must {
"properly prepend reversed message lists to the front" in {
- val create0 = Failed(child, null, 0)
- val create1 = Failed(child, null, 1)
- val create2 = Failed(child, null, 2)
- val create3 = Failed(child, null, 3)
- val create4 = Failed(child, null, 4)
- val create5 = Failed(child, null, 5)
+ val create0: akka.dispatch.sysmsg.Failed = Failed(child, null, 0)
+ val create1: akka.dispatch.sysmsg.Failed = Failed(child, null, 1)
+ val create2: akka.dispatch.sysmsg.Failed = Failed(child, null, 2)
+ val create3: akka.dispatch.sysmsg.Failed = Failed(child, null, 3)
+ val create4: akka.dispatch.sysmsg.Failed = Failed(child, null, 4)
+ val create5: akka.dispatch.sysmsg.Failed = Failed(child, null, 5)
- val fwdList = create3 :: create4 :: create5 :: ENil
- val revList = create2 :: create1 :: create0 :: LNil
+ val fwdList: akka.dispatch.sysmsg.EarliestFirstSystemMessageList = create3 :: create4 :: create5 :: ENil
+ val revList: akka.dispatch.sysmsg.LatestFirstSystemMessageList = create2 :: create1 :: create0 :: LNil
- val list = revList reverse_::: fwdList
+ val list: akka.dispatch.sysmsg.EarliestFirstSystemMessageList = revList reverse_::: fwdList
(list.head eq create0) should ===(true)
(list.tail.head eq create1) should ===(true)
diff --git a/akka-actor-tests/src/test/scala/akka/event/AddressTerminatedTopicBenchSpec.scala b/akka-actor-tests/src/test/scala/akka/event/AddressTerminatedTopicBenchSpec.scala
index 4c713af..ee4c71a 100644
--- a/akka-actor-tests/src/test/scala/akka/event/AddressTerminatedTopicBenchSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/AddressTerminatedTopicBenchSpec.scala
@@ -20,7 +20,7 @@ object AddressTerminatedTopicBenchSpec {
AddressTerminatedTopic(context.system).unsubscribe(self)
}
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}
}
@@ -30,17 +30,17 @@ class AddressTerminatedTopicBenchSpec extends AkkaSpec("akka.loglevel=INFO") {
"Subscribe and unsubscribe of AddressTerminated" must {
"be quick" in {
- val sys = ActorSystem(system.name + "2", system.settings.config)
+ val sys: akka.actor.ActorSystem = ActorSystem(system.name + "2", system.settings.config)
try {
val num = 20000
- val t1 = System.nanoTime()
- val p = Props(classOf[Subscriber], testActor)
- val subscribers = Vector.fill(num)(sys.actorOf(p))
+ val t1: Long = System.nanoTime()
+ val p: akka.actor.Props = Props(classOf[Subscriber], testActor)
+ val subscribers: scala.collection.immutable.Vector[akka.actor.ActorRef] = Vector.fill(num)(sys.actorOf(p))
receiveN(num, 10.seconds)
log.info("Starting {} actors took {} ms", num, (System.nanoTime() - t1).nanos.toMillis)
- val t2 = System.nanoTime()
+ val t2: Long = System.nanoTime()
shutdown(sys, 10.seconds, verifySystemShutdown = true)
log.info("Stopping {} actors took {} ms", num, (System.nanoTime() - t2).nanos.toMillis)
} finally {
diff --git a/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala b/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala
index b9ee835..d5cdd54 100644
--- a/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala
@@ -16,7 +16,7 @@ import com.typesafe.config.{ Config, ConfigFactory }
object EventBusSpec {
class TestActorWrapperActor(testActor: ActorRef) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x ⇒ testActor forward x
}
}
@@ -35,17 +35,17 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty(
def disposeSubscriber(system: ActorSystem, subscriber: BusType#Subscriber): Unit
- lazy val bus = createNewEventBus()
+ lazy val bus: EventBusSpec.this.BusType = createNewEventBus()
busName must {
- def createNewSubscriber() = createSubscriber(testActor).asInstanceOf[bus.Subscriber]
- def getClassifierFor(event: BusType#Event) = classifierFor(event).asInstanceOf[bus.Classifier]
+ def createNewSubscriber(): EventBusSpec.this.bus.Subscriber = createSubscriber(testActor).asInstanceOf[bus.Subscriber]
+ def getClassifierFor(event: BusType#Event): EventBusSpec.this.bus.Classifier = classifierFor(event).asInstanceOf[bus.Classifier]
def createNewEvents(numberOfEvents: Int): Iterable[bus.Event] = createEvents(numberOfEvents).asInstanceOf[Iterable[bus.Event]]
- val events = createNewEvents(100)
- val event = events.head
- val classifier = getClassifierFor(event)
- val subscriber = createNewSubscriber()
+ val events: Iterable[EventBusSpec.this.bus.Event] = createNewEvents(100)
+ val event: EventBusSpec.this.bus.Event = events.head
+ val classifier: EventBusSpec.this.bus.Classifier = getClassifierFor(event)
+ val subscriber: EventBusSpec.this.bus.Subscriber = createNewSubscriber()
"allow subscribers" in {
bus.subscribe(subscriber, classifier) should ===(true)
@@ -56,7 +56,7 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty(
}
"not allow to unsubscribe non-existing subscriber" in {
- val sub = createNewSubscriber()
+ val sub: EventBusSpec.this.bus.Subscriber = createNewSubscriber()
bus.unsubscribe(sub, classifier) should ===(false)
disposeSubscriber(system, sub)
}
@@ -74,9 +74,9 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty(
}
"allow to add multiple subscribers" in {
- val subscribers = (1 to 10) map { _ ⇒ createNewSubscriber() }
- val events = createEvents(10)
- val classifiers = events map getClassifierFor
+ val subscribers: scala.collection.immutable.IndexedSeq[EventBusSpec.this.bus.Subscriber] = (1 to 10) map { _ ⇒ createNewSubscriber() }
+ val events: Iterable[EventBusSpec.this.BusType#Event] = createEvents(10)
+ val classifiers: Iterable[EventBusSpec.this.bus.Classifier] = events map getClassifierFor
subscribers.zip(classifiers) forall { case (s, c) ⇒ bus.subscribe(s, c) } should ===(true)
subscribers.zip(classifiers) forall { case (s, c) ⇒ bus.unsubscribe(s, c) } should ===(true)
@@ -108,8 +108,8 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty(
}
"publish the given event to all intended subscribers" in {
- val range = 0 until 10
- val subscribers = range map (_ ⇒ createNewSubscriber())
+ val range: scala.collection.immutable.Range = 0 until 10
+ val subscribers: scala.collection.immutable.IndexedSeq[EventBusSpec.this.bus.Subscriber] = range map (_ ⇒ createNewSubscriber())
subscribers foreach { s ⇒ bus.subscribe(s, classifier) should ===(true) }
bus.publish(event)
range foreach { _ ⇒ expectMsg(event) }
@@ -117,8 +117,8 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty(
}
"not publish the given event to any other subscribers than the intended ones" in {
- val otherSubscriber = createNewSubscriber()
- val otherClassifier = getClassifierFor(events.drop(1).head)
+ val otherSubscriber: EventBusSpec.this.bus.Subscriber = createNewSubscriber()
+ val otherClassifier: EventBusSpec.this.bus.Classifier = getClassifierFor(events.drop(1).head)
bus.subscribe(subscriber, classifier)
bus.subscribe(otherSubscriber, otherClassifier)
bus.publish(event)
@@ -147,9 +147,9 @@ object ActorEventBusSpec {
type Event = Notification
- def classify(event: Event) = event.ref
+ def classify(event: Event): akka.actor.ActorRef = event.ref
protected def mapSize = 32
- def publish(event: Event, subscriber: Subscriber) = subscriber ! event
+ def publish(event: Event, subscriber: Subscriber): Unit = subscriber ! event
}
case class Notification(ref: ActorRef, payload: Int)
@@ -167,21 +167,21 @@ class ActorEventBusSpec(conf: Config) extends EventBusSpec("ActorEventBus", conf
def createNewEventBus(): BusType = new MyActorEventBus(system)
// different actor in each event because we want each event to have a different classifier (see EventBusSpec tests)
- def createEvents(numberOfEvents: Int) = (0 until numberOfEvents).map(Notification(TestProbe().ref, _)).toSeq
+ def createEvents(numberOfEvents: Int): scala.collection.immutable.Seq[akka.event.ActorEventBusSpec.Notification] = (0 until numberOfEvents).map(Notification(TestProbe().ref, _)).toSeq
- def createSubscriber(pipeTo: ActorRef) = system.actorOf(Props(new TestActorWrapperActor(pipeTo)))
+ def createSubscriber(pipeTo: ActorRef): akka.actor.ActorRef = system.actorOf(Props(new TestActorWrapperActor(pipeTo)))
- def classifierFor(event: BusType#Event) = event.ref
+ def classifierFor(event: BusType#Event): akka.actor.ActorRef = event.ref
def disposeSubscriber(system: ActorSystem, subscriber: BusType#Subscriber): Unit = system.stop(subscriber)
// ManagedActorClassification specific tests
"must unsubscribe subscriber when it terminates" in {
- val a1 = createSubscriber(system.deadLetters)
- val subs = createSubscriber(testActor)
- def m(i: Int) = Notification(a1, i)
- val p = TestProbe()
+ val a1: akka.actor.ActorRef = createSubscriber(system.deadLetters)
+ val subs: akka.actor.ActorRef = createSubscriber(testActor)
+ def m(i: Int): akka.event.ActorEventBusSpec.Notification = Notification(a1, i)
+ val p: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(p.ref, classOf[Logging.Debug])
bus.subscribe(subs, a1)
@@ -204,9 +204,9 @@ class ActorEventBusSpec(conf: Config) extends EventBusSpec("ActorEventBus", conf
// Deaths of monitored actors should not influence the subscription.
// For example: one might still want to monitor messages classified to A
// even though it died, and handle these in some way.
- val a1 = createSubscriber(system.deadLetters)
- val subs = createSubscriber(testActor)
- def m(i: Int) = Notification(a1, i)
+ val a1: akka.actor.ActorRef = createSubscriber(system.deadLetters)
+ val subs: akka.actor.ActorRef = createSubscriber(testActor)
+ def m(i: Int): akka.event.ActorEventBusSpec.Notification = Notification(a1, i)
bus.subscribe(subs, a1) should equal(true)
@@ -226,11 +226,11 @@ class ActorEventBusSpec(conf: Config) extends EventBusSpec("ActorEventBus", conf
"must unregister subscriber only after it unsubscribes from all of it's subscriptions" in {
val a1, a2 = createSubscriber(system.deadLetters)
- val subs = createSubscriber(testActor)
- def m1(i: Int) = Notification(a1, i)
- def m2(i: Int) = Notification(a2, i)
+ val subs: akka.actor.ActorRef = createSubscriber(testActor)
+ def m1(i: Int): akka.event.ActorEventBusSpec.Notification = Notification(a1, i)
+ def m2(i: Int): akka.event.ActorEventBusSpec.Notification = Notification(a2, i)
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(p.ref, classOf[Logging.Debug])
bus.subscribe(subs, a1) should equal(true)
@@ -259,7 +259,7 @@ class ActorEventBusSpec(conf: Config) extends EventBusSpec("ActorEventBus", conf
}
private def expectUnsubscribedByUnsubscriber(p: TestProbe, a: ActorRef) {
- val expectedMsg = s"actor $a has terminated, unsubscribing it from $bus"
+ val expectedMsg: String = s"actor $a has terminated, unsubscribing it from $bus"
p.fishForMessage(1 second, hint = expectedMsg) {
case Logging.Debug(_, _, msg) if msg equals expectedMsg ⇒ true
case other ⇒ false
@@ -267,7 +267,7 @@ class ActorEventBusSpec(conf: Config) extends EventBusSpec("ActorEventBus", conf
}
private def expectUnregisterFromUnsubscriber(p: TestProbe, a: ActorRef) {
- val expectedMsg = s"unregistered watch of $a in $bus"
+ val expectedMsg: String = s"unregistered watch of $a in $bus"
p.fishForMessage(1 second, hint = expectedMsg) {
case Logging.Debug(_, _, msg) if msg equals expectedMsg ⇒ true
case other ⇒ false
@@ -298,11 +298,11 @@ class ScanningEventBusSpec extends EventBusSpec("ScanningEventBus") {
def createNewEventBus(): BusType = new MyScanningEventBus
- def createEvents(numberOfEvents: Int) = (0 until numberOfEvents)
+ def createEvents(numberOfEvents: Int): scala.collection.immutable.Range = (0 until numberOfEvents)
- def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
+ def createSubscriber(pipeTo: ActorRef): akka.japi.Procedure[Int] = new Procedure[Int] { def apply(i: Int): Unit = pipeTo ! i }
- def classifierFor(event: BusType#Event) = event.toString
+ def classifierFor(event: BusType#Event): String = event.toString
def disposeSubscriber(system: ActorSystem, subscriber: BusType#Subscriber): Unit = ()
}
@@ -329,11 +329,11 @@ class LookupEventBusSpec extends EventBusSpec("LookupEventBus") {
def createNewEventBus(): BusType = new MyLookupEventBus
- def createEvents(numberOfEvents: Int) = (0 until numberOfEvents)
+ def createEvents(numberOfEvents: Int): scala.collection.immutable.Range = (0 until numberOfEvents)
- def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
+ def createSubscriber(pipeTo: ActorRef): akka.japi.Procedure[Int] = new Procedure[Int] { def apply(i: Int): Unit = pipeTo ! i }
- def classifierFor(event: BusType#Event) = event.toString
+ def classifierFor(event: BusType#Event): String = event.toString
def disposeSubscriber(system: ActorSystem, subscriber: BusType#Subscriber): Unit = ()
}
diff --git a/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala b/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala
index f3da453..d12c162 100644
--- a/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala
@@ -12,7 +12,7 @@ import akka.testkit.{ TestProbe, AkkaSpec }
object EventStreamSpec {
- val config = ConfigFactory.parseString("""
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
actor.serialize-messages = off
stdout-loglevel = WARNING
@@ -21,7 +21,7 @@ object EventStreamSpec {
}
""".format(Logging.StandardOutLogger.getClass.getName))
- val configUnhandled = ConfigFactory.parseString("""
+ val configUnhandled: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
actor.serialize-messages = off
stdout-loglevel = WARNING
@@ -30,7 +30,7 @@ object EventStreamSpec {
}
""")
- val configUnhandledWithDebug =
+ val configUnhandledWithDebug: com.typesafe.config.Config =
ConfigFactory.parseString("akka.actor.debug.event-stream = on")
.withFallback(configUnhandled)
@@ -40,7 +40,7 @@ object EventStreamSpec {
class MyLog extends Actor {
var dst: ActorRef = context.system.deadLetters
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Logging.InitializeLogger(bus) ⇒
bus.subscribe(context.self, classOf[SetTarget])
bus.subscribe(context.self, classOf[UnhandledMessage])
@@ -70,13 +70,13 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
import EventStreamSpec._
- val impl = system.asInstanceOf[ActorSystemImpl]
+ val impl: akka.actor.ActorSystemImpl = system.asInstanceOf[ActorSystemImpl]
"An EventStream" must {
"manage subscriptions" in {
//#event-bus-start-unsubscriber-scala
- val bus = new EventStream(system, true)
+ val bus: akka.event.EventStream = new EventStream(system, true)
bus.startUnsubscriber()
//#event-bus-start-unsubscriber-scala
@@ -91,21 +91,21 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"not allow null as subscriber" in {
- val bus = new EventStream(system, true)
+ val bus: akka.event.EventStream = new EventStream(system, true)
intercept[IllegalArgumentException] { bus.subscribe(null, classOf[M]) }.getMessage should ===("subscriber is null")
}
"not allow null as unsubscriber" in {
- val bus = new EventStream(system, true)
+ val bus: akka.event.EventStream = new EventStream(system, true)
intercept[IllegalArgumentException] { bus.unsubscribe(null, classOf[M]) }.getMessage should ===("subscriber is null")
intercept[IllegalArgumentException] { bus.unsubscribe(null) }.getMessage should ===("subscriber is null")
}
"be able to log unhandled messages" in {
- val sys = ActorSystem("EventStreamSpecUnhandled", configUnhandled)
+ val sys: akka.actor.ActorSystem = ActorSystem("EventStreamSpecUnhandled", configUnhandled)
try {
sys.eventStream.subscribe(testActor, classOf[AnyRef])
- val m = UnhandledMessage(42, sys.deadLetters, sys.deadLetters)
+ val m: akka.actor.UnhandledMessage = UnhandledMessage(42, sys.deadLetters, sys.deadLetters)
sys.eventStream.publish(m)
expectMsgAllOf(m, Logging.Debug(sys.deadLetters.path.toString, sys.deadLetters.getClass, "unhandled message from " + sys.deadLetters + ": 42"))
sys.eventStream.unsubscribe(testActor)
@@ -115,7 +115,7 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage log levels" in {
- val bus = new EventStream(system, false)
+ val bus: akka.event.EventStream = new EventStream(system, false)
bus.startDefaultLoggers(impl)
bus.publish(SetTarget(testActor))
expectMsg("OK")
@@ -132,11 +132,11 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes" in {
- val a = new A
- val b1 = new B2
- val b2 = new B3
- val c = new C
- val bus = new EventStream(system, false)
+ val a: akka.event.EventStreamSpec.A = new A
+ val b1: akka.event.EventStreamSpec.B2 = new B2
+ val b2: akka.event.EventStreamSpec.B3 = new B3
+ val c: akka.event.EventStreamSpec.C = new C
+ val bus: akka.event.EventStream = new EventStream(system, false)
within(2 seconds) {
bus.subscribe(testActor, classOf[B3]) should ===(true)
bus.publish(c)
@@ -158,9 +158,9 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes and traits (update on subscribe)" in {
- val es = new EventStream(system, false)
- val tm1 = new CC
- val tm2 = new CCATBT
+ val es: akka.event.EventStream = new EventStream(system, false)
+ val tm1: akka.event.EventStreamSpec.CC = new CC
+ val tm2: akka.event.EventStreamSpec.CCATBT = new CCATBT
val a1, a2, a3, a4 = TestProbe()
es.subscribe(a1.ref, classOf[AT]) should ===(true)
@@ -181,9 +181,9 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes and traits (update on unsubscribe)" in {
- val es = new EventStream(system, false)
- val tm1 = new CC
- val tm2 = new CCATBT
+ val es: akka.event.EventStream = new EventStream(system, false)
+ val tm1: akka.event.EventStreamSpec.CC = new CC
+ val tm2: akka.event.EventStreamSpec.CCATBT = new CCATBT
val a1, a2, a3, a4 = TestProbe()
es.subscribe(a1.ref, classOf[AT]) should ===(true)
@@ -203,9 +203,9 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes and traits (update on unsubscribe all)" in {
- val es = new EventStream(system, false)
- val tm1 = new CC
- val tm2 = new CCATBT
+ val es: akka.event.EventStream = new EventStream(system, false)
+ val tm1: akka.event.EventStreamSpec.CC = new CC
+ val tm2: akka.event.EventStreamSpec.CCATBT = new CCATBT
val a1, a2, a3, a4 = TestProbe()
es.subscribe(a1.ref, classOf[AT]) should ===(true)
@@ -225,9 +225,9 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes and traits (update on publish)" in {
- val es = new EventStream(system, false)
- val tm1 = new CC
- val tm2 = new CCATBT
+ val es: akka.event.EventStream = new EventStream(system, false)
+ val tm1: akka.event.EventStreamSpec.CC = new CC
+ val tm2: akka.event.EventStreamSpec.CCATBT = new CCATBT
val a1, a2 = TestProbe()
es.subscribe(a1.ref, classOf[AT]) should ===(true)
@@ -241,9 +241,9 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes and traits (unsubscribe classes used with trait)" in {
- val es = new EventStream(system, false)
- val tm1 = new CC
- val tm2 = new CCATBT
+ val es: akka.event.EventStream = new EventStream(system, false)
+ val tm1: akka.event.EventStreamSpec.CC = new CC
+ val tm2: akka.event.EventStreamSpec.CCATBT = new CCATBT
val a1, a2, a3 = TestProbe()
es.subscribe(a1.ref, classOf[AT]) should ===(true)
@@ -263,8 +263,8 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"manage sub-channels using classes and traits (subscribe after publish)" in {
- val es = new EventStream(system, false)
- val tm1 = new CCATBT
+ val es: akka.event.EventStream = new EventStream(system, false)
+ val tm1: akka.event.EventStreamSpec.CCATBT = new CCATBT
val a1, a2 = TestProbe()
es.subscribe(a1.ref, classOf[AT]) should ===(true)
@@ -280,15 +280,15 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"unsubscribe an actor on its termination" in {
- val sys = ActorSystem("EventStreamSpecUnsubscribeOnTerminated", configUnhandledWithDebug)
+ val sys: akka.actor.ActorSystem = ActorSystem("EventStreamSpecUnsubscribeOnTerminated", configUnhandledWithDebug)
try {
- val es = sys.eventStream
+ val es: akka.event.EventStream = sys.eventStream
val a1, a2 = TestProbe()
- val tm = new A
+ val tm: akka.event.EventStreamSpec.A = new A
- val target = sys.actorOf(Props(new Actor {
- def receive = { case in ⇒ a1.ref forward in }
+ val target: akka.actor.ActorRef = sys.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case in ⇒ a1.ref forward in }
}), "to-be-killed")
es.subscribe(a2.ref, classOf[Any])
@@ -309,14 +309,14 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"unsubscribe the actor, when it subscribes already in terminated state" in {
- val sys = ActorSystem("EventStreamSpecUnsubscribeTerminated", configUnhandledWithDebug)
+ val sys: akka.actor.ActorSystem = ActorSystem("EventStreamSpecUnsubscribeTerminated", configUnhandledWithDebug)
try {
- val es = sys.eventStream
+ val es: akka.event.EventStream = sys.eventStream
val a1, a2 = TestProbe()
- val target = system.actorOf(Props(new Actor {
- def receive = { case in ⇒ a1.ref forward in }
+ val target: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case in ⇒ a1.ref forward in }
}), "to-be-killed")
watch(target)
@@ -337,14 +337,14 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"not allow initializing a TerminatedUnsubscriber twice" in {
- val sys = ActorSystem("MustNotAllowDoubleInitOfTerminatedUnsubscriber", config)
+ val sys: akka.actor.ActorSystem = ActorSystem("MustNotAllowDoubleInitOfTerminatedUnsubscriber", config)
// initializes an TerminatedUnsubscriber during start
try {
- val es = sys.eventStream
- val p = TestProbe()
+ val es: akka.event.EventStream = sys.eventStream
+ val p: akka.testkit.TestProbe = TestProbe()
- val refWillBeUsedAsUnsubscriber = es.initUnsubscriber(p.ref)
+ val refWillBeUsedAsUnsubscriber: Boolean = es.initUnsubscriber(p.ref)
refWillBeUsedAsUnsubscriber should equal(false)
@@ -354,10 +354,10 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"unwatch an actor from unsubscriber when that actor unsubscribes from the stream" in {
- val sys = ActorSystem("MustUnregisterDuringUnsubscribe", configUnhandledWithDebug)
+ val sys: akka.actor.ActorSystem = ActorSystem("MustUnregisterDuringUnsubscribe", configUnhandledWithDebug)
try {
- val es = sys.eventStream
+ val es: akka.event.EventStream = sys.eventStream
val a1, a2 = TestProbe()
es.subscribe(a1.ref, classOf[Logging.Debug])
@@ -374,10 +374,10 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
}
"unwatch an actor from unsubscriber when that actor unsubscribes from channels it subscribed" in {
- val sys = ActorSystem("MustUnregisterWhenNoMoreChannelSubscriptions", configUnhandledWithDebug)
+ val sys: akka.actor.ActorSystem = ActorSystem("MustUnregisterWhenNoMoreChannelSubscriptions", configUnhandledWithDebug)
try {
- val es = sys.eventStream
+ val es: akka.event.EventStream = sys.eventStream
val a1, a2 = TestProbe()
es.subscribe(a1.ref, classOf[Logging.Debug])
@@ -407,8 +407,8 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
private def verifyLevel(bus: LoggingBus, level: Logging.LogLevel) {
import Logging._
- val allmsg = Seq(Debug("", null, "debug"), Info("", null, "info"), Warning("", null, "warning"), Error("", null, "error"))
- val msg = allmsg filter (_.level <= level)
+ val allmsg: Seq[akka.event.Logging.LogEvent with Product with Serializable] = Seq(Debug("", null, "debug"), Info("", null, "info"), Warning("", null, "warning"), Error("", null, "error"))
+ val msg: Seq[akka.event.Logging.LogEvent with Product with Serializable] = allmsg filter (_.level <= level)
allmsg foreach bus.publish
msg foreach (expectMsg(_))
}
diff --git a/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala b/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala
index 570ae31..c54cfd5 100644
--- a/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala
@@ -23,7 +23,7 @@ import java.text.SimpleDateFormat
object LoggerSpec {
- val defaultConfig = ConfigFactory.parseString("""
+ val defaultConfig: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
stdout-loglevel = "WARNING"
loglevel = "DEBUG"
@@ -31,7 +31,7 @@ object LoggerSpec {
}
""").withFallback(AkkaSpec.testConf)
- val slowConfig = ConfigFactory.parseString("""
+ val slowConfig: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
stdout-loglevel = "ERROR"
loglevel = "ERROR"
@@ -39,7 +39,7 @@ object LoggerSpec {
}
""").withFallback(AkkaSpec.testConf)
- val noLoggingConfig = ConfigFactory.parseString("""
+ val noLoggingConfig: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
stdout-loglevel = "OFF"
loglevel = "OFF"
@@ -47,7 +47,7 @@ object LoggerSpec {
}
""").withFallback(AkkaSpec.testConf)
- val multipleConfig = ConfigFactory.parseString("""
+ val multipleConfig: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
stdout-loglevel = "OFF"
loglevel = "WARNING"
@@ -55,7 +55,7 @@ object LoggerSpec {
}
""").withFallback(AkkaSpec.testConf)
- val ticket3165Config = ConfigFactory.parseString(s"""
+ val ticket3165Config: com.typesafe.config.Config = ConfigFactory.parseString(s"""
akka {
stdout-loglevel = "WARNING"
loglevel = "DEBUG"
@@ -70,7 +70,7 @@ object LoggerSpec {
}
""").withFallback(AkkaSpec.testConf)
- val ticket3671Config = ConfigFactory.parseString("""
+ val ticket3671Config: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
stdout-loglevel = "WARNING"
loglevel = "WARNING"
@@ -121,9 +121,9 @@ object LoggerSpec {
override def mdc(currentMessage: Any): MDC = {
reqId += 1
- val always = Map("requestId" → reqId)
+ val always: scala.collection.immutable.Map[String, Int] = Map("requestId" → reqId)
val cmim = "Current Message in MDC"
- val perMessage = currentMessage match {
+ val perMessage: scala.collection.immutable.Map[_ <: String, Any] = currentMessage match {
case `cmim` ⇒ Map[String, Any]("currentMsg" → cmim, "currentMsgLength" → cmim.length)
case _ ⇒ Map()
}
@@ -142,11 +142,11 @@ class LoggerSpec extends WordSpec with Matchers {
import LoggerSpec._
private def createSystemAndLogToBuffer(name: String, config: Config, shouldLog: Boolean) = {
- val out = new java.io.ByteArrayOutputStream()
+ val out: java.io.ByteArrayOutputStream = new java.io.ByteArrayOutputStream()
Console.withOut(out) {
- implicit val system = ActorSystem(name, config)
+ implicit val system: akka.actor.ActorSystem = ActorSystem(name, config)
try {
- val probe = TestProbe()
+ val probe: akka.testkit.TestProbe = TestProbe()
system.eventStream.publish(SetTarget(probe.ref, qualifier = 1))
probe.expectMsg("OK")
system.log.error("Danger! Danger!")
@@ -169,14 +169,14 @@ class LoggerSpec extends WordSpec with Matchers {
"A normally configured actor system" must {
"log messages to standard output" in {
- val out = createSystemAndLogToBuffer("defaultLogger", defaultConfig, true)
+ val out: java.io.ByteArrayOutputStream = createSystemAndLogToBuffer("defaultLogger", defaultConfig, true)
out.size should be > (0)
}
"drain logger queue on system.terminate" in {
- val out = new java.io.ByteArrayOutputStream()
+ val out: java.io.ByteArrayOutputStream = new java.io.ByteArrayOutputStream()
Console.withOut(out) {
- val sys = ActorSystem("defaultLogger", slowConfig)
+ val sys: akka.actor.ActorSystem = ActorSystem("defaultLogger", slowConfig)
sys.log.error("msg1")
sys.log.error("msg2")
sys.log.error("msg3")
@@ -185,7 +185,7 @@ class LoggerSpec extends WordSpec with Matchers {
out.close()
}
- val logMessages = new String(out.toByteArray).split("\n")
+ val logMessages: Array[String] = new String(out.toByteArray).split("\n")
logMessages.head should include("msg1")
logMessages.last should include("msg3")
logMessages.size should ===(3)
@@ -196,7 +196,7 @@ class LoggerSpec extends WordSpec with Matchers {
"An actor system configured with the logging turned off" must {
"not log messages to standard output" in {
- val out = createSystemAndLogToBuffer("noLogging", noLoggingConfig, false)
+ val out: java.io.ByteArrayOutputStream = createSystemAndLogToBuffer("noLogging", noLoggingConfig, false)
out.size should ===(0)
}
}
@@ -205,10 +205,10 @@ class LoggerSpec extends WordSpec with Matchers {
"use several loggers" in {
Console.withOut(new java.io.ByteArrayOutputStream()) {
- implicit val system = ActorSystem("multipleLoggers", multipleConfig)
+ implicit val system: akka.actor.ActorSystem = ActorSystem("multipleLoggers", multipleConfig)
try {
- val probe1 = TestProbe()
- val probe2 = TestProbe()
+ val probe1: akka.testkit.TestProbe = TestProbe()
+ val probe2: akka.testkit.TestProbe = TestProbe()
system.eventStream.publish(SetTarget(probe1.ref, qualifier = 1))
probe1.expectMsg("OK")
system.eventStream.publish(SetTarget(probe2.ref, qualifier = 2))
@@ -227,13 +227,13 @@ class LoggerSpec extends WordSpec with Matchers {
"Ticket 3671" must {
"log message with given MDC values" in {
- implicit val system = ActorSystem("ticket-3671", ticket3671Config)
+ implicit val system: akka.actor.ActorSystem = ActorSystem("ticket-3671", ticket3671Config)
try {
- val probe = TestProbe()
+ val probe: akka.testkit.TestProbe = TestProbe()
system.eventStream.publish(SetTarget(probe.ref, qualifier = 1))
probe.expectMsg("OK")
- val ref = system.actorOf(Props[ActorWithMDC])
+ val ref: akka.actor.ActorRef = system.actorOf(Props[ActorWithMDC])
ref ! "Processing new Request"
probe.expectMsgPF(max = 3.seconds) {
@@ -267,32 +267,32 @@ class LoggerSpec extends WordSpec with Matchers {
"Ticket 3080" must {
"format currentTimeMillis to a valid UTC String" in {
- val timestamp = System.currentTimeMillis
- val c = new GregorianCalendar(TimeZone.getTimeZone("UTC"))
+ val timestamp: Long = System.currentTimeMillis
+ val c: java.util.GregorianCalendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"))
c.setTime(new Date(timestamp))
- val hours = c.get(Calendar.HOUR_OF_DAY)
- val minutes = c.get(Calendar.MINUTE)
- val seconds = c.get(Calendar.SECOND)
- val ms = c.get(Calendar.MILLISECOND)
+ val hours: Int = c.get(Calendar.HOUR_OF_DAY)
+ val minutes: Int = c.get(Calendar.MINUTE)
+ val seconds: Int = c.get(Calendar.SECOND)
+ val ms: Int = c.get(Calendar.MILLISECOND)
Helpers.currentTimeMillisToUTCString(timestamp) should ===(f"$hours%02d:$minutes%02d:$seconds%02d.$ms%03dUTC")
}
}
"StdOutLogger" must {
"format timestamp to with system default TimeZone" in {
- val log = new StdOutLogger {}
- val event = Info("test", classOf[String], "test")
+ val log: akka.event.Logging.StdOutLogger = new StdOutLogger {}
+ val event: akka.event.Logging.Info = Info("test", classOf[String], "test")
// this was the format in Akka 2.4 and earlier
- val dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS")
- val expected = dateFormat.format(new Date(event.timestamp))
+ val dateFormat: java.text.SimpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS")
+ val expected: String = dateFormat.format(new Date(event.timestamp))
log.timestamp(event) should ===(expected)
}
"include the cause message in the log message even exceptions with no stack trace" in {
class MyCause(msg: String) extends RuntimeException(msg) with NoStackTrace
- val log = new StdOutLogger {}
- val out = new java.io.ByteArrayOutputStream()
+ val log: akka.event.Logging.StdOutLogger = new StdOutLogger {}
+ val out: java.io.ByteArrayOutputStream = new java.io.ByteArrayOutputStream()
val causeMessage = "Some details about the exact cause"
@@ -308,7 +308,7 @@ class LoggerSpec extends WordSpec with Matchers {
"Ticket 3165 - serialize-messages and dual-entry serialization of LogEvent" must {
"not cause StackOverflowError" in {
- implicit val s = ActorSystem("foo", ticket3165Config)
+ implicit val s: akka.actor.ActorSystem = ActorSystem("foo", ticket3165Config)
try {
SerializationExtension(s).serialize(Warning("foo", classOf[String]))
} finally {
diff --git a/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala b/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala
index f505cb3..11163af 100644
--- a/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala
@@ -16,24 +16,24 @@ import scala.annotation.tailrec
object LoggingReceiveSpec {
class TestLogActor extends Actor {
- override val supervisorStrategy =
+ override val supervisorStrategy: akka.actor.OneForOneStrategy =
OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 5 seconds)(List(classOf[Throwable]))
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
}
class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
import LoggingReceiveSpec._
- val config = ConfigFactory.parseString("""
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.loglevel=DEBUG
akka.actor.serialize-messages = off # debug noise from serialization
""").withFallback(AkkaSpec.testConf)
- val appLogging = ActorSystem("logging", ConfigFactory.parseMap(Map("akka.actor.debug.receive" → true).asJava).withFallback(config))
- val appAuto = ActorSystem("autoreceive", ConfigFactory.parseMap(Map("akka.actor.debug.autoreceive" → true).asJava).withFallback(config))
- val appLifecycle = ActorSystem("lifecycle", ConfigFactory.parseMap(Map("akka.actor.debug.lifecycle" → true).asJava).withFallback(config))
+ val appLogging: akka.actor.ActorSystem = ActorSystem("logging", ConfigFactory.parseMap(Map("akka.actor.debug.receive" → true).asJava).withFallback(config))
+ val appAuto: akka.actor.ActorSystem = ActorSystem("autoreceive", ConfigFactory.parseMap(Map("akka.actor.debug.autoreceive" → true).asJava).withFallback(config))
+ val appLifecycle: akka.actor.ActorSystem = ActorSystem("lifecycle", ConfigFactory.parseMap(Map("akka.actor.debug.lifecycle" → true).asJava).withFallback(config))
- val filter = TestEvent.Mute(EventFilter.custom {
+ val filter: akka.testkit.TestEvent.Mute = TestEvent.Mute(EventFilter.custom {
case _: Logging.Debug ⇒ true
case _: Logging.Info ⇒ true
case _ ⇒ false
@@ -60,8 +60,8 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
new TestKit(appLogging) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
system.eventStream.subscribe(testActor, classOf[UnhandledMessage])
- val a = system.actorOf(Props(new Actor {
- def receive = new LoggingReceive(Some("funky"), {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: akka.event.LoggingReceive = new LoggingReceive(Some("funky"), {
case null ⇒
})
}))
@@ -82,14 +82,14 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
case null ⇒
}
- val actor = TestActorRef(new Actor {
+ val actor: akka.testkit.TestActorRef[akka.actor.Actor { def switch: akka.actor.Actor.Receive }] = TestActorRef(new Actor {
def switch: Actor.Receive = { case "becomenull" ⇒ context.become(r, false) }
- def receive = switch orElse LoggingReceive {
+ def receive: PartialFunction[Any, Unit] = switch orElse LoggingReceive {
case x ⇒ sender() ! "x"
}
})
- val name = actor.path.toString
+ val name: String = actor.path.toString
actor ! "buh"
expectMsg(Logging.Debug(actor.path.toString, actor.underlyingActor.getClass,
"received handled message buh from " + self))
@@ -107,8 +107,8 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
"not duplicate logging" in {
new TestKit(appLogging) with ImplicitSender {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
- val actor = TestActorRef(new Actor {
- def receive = LoggingReceive(LoggingReceive {
+ val actor: akka.testkit.TestActorRef[akka.actor.Actor] = TestActorRef(new Actor {
+ def receive: akka.actor.Actor.Receive = LoggingReceive(LoggingReceive {
case _ ⇒ sender() ! "x"
})
})
@@ -122,10 +122,10 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
"log with MDC" in {
new TestKit(appLogging) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
- val myMDC = Map("hello" → "mdc")
- val a = system.actorOf(Props(new Actor with DiagnosticActorLogging {
- override def mdc(currentMessage: Any) = myMDC
- def receive = LoggingReceive {
+ val myMDC: scala.collection.immutable.Map[String, String] = Map("hello" → "mdc")
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor with DiagnosticActorLogging {
+ override def mdc(currentMessage: Any): scala.collection.immutable.Map[String, String] = myMDC
+ def receive: akka.actor.Actor.Receive = LoggingReceive {
case "hello" ⇒
}
}))
@@ -139,8 +139,8 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
"support various log level" in {
new TestKit(appLogging) with ImplicitSender {
system.eventStream.subscribe(testActor, classOf[Logging.Info])
- val actor = TestActorRef(new Actor {
- def receive = LoggingReceive(Logging.InfoLevel) {
+ val actor: akka.testkit.TestActorRef[akka.actor.Actor] = TestActorRef(new Actor {
+ def receive: akka.actor.Actor.Receive = LoggingReceive(Logging.InfoLevel) {
case _ ⇒ sender() ! "x"
}
})
@@ -158,12 +158,12 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
"log AutoReceiveMessages if requested" in {
new TestKit(appAuto) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
- val actor = TestActorRef(new Actor {
- def receive = {
+ val actor: akka.testkit.TestActorRef[akka.actor.Actor] = TestActorRef(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case _ ⇒
}
})
- val name = actor.path.toString
+ val name: String = actor.path.toString
actor ! PoisonPill
fishForMessage(hint = "received AutoReceiveMessage Envelope(PoisonPill") {
case Logging.Debug(`name`, _, msg: String) if msg startsWith "received AutoReceiveMessage Envelope(PoisonPill" ⇒ true
@@ -177,10 +177,10 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
new TestKit(appLifecycle) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
within(3 seconds) {
- val lifecycleGuardian = appLifecycle.asInstanceOf[ActorSystemImpl].guardian
- val lname = lifecycleGuardian.path.toString
- val supervisor = TestActorRef[TestLogActor](Props[TestLogActor])
- val sname = supervisor.path.toString
+ val lifecycleGuardian: akka.actor.LocalActorRef = appLifecycle.asInstanceOf[ActorSystemImpl].guardian
+ val lname: String = lifecycleGuardian.path.toString
+ val supervisor: akka.testkit.TestActorRef[akka.event.LoggingReceiveSpec.TestLogActor] = TestActorRef[TestLogActor](Props[TestLogActor])
+ val sname: String = supervisor.path.toString
fishForMessage(hint = "now supervising") {
case Logging.Debug(`lname`, _, msg: String) if msg startsWith "now supervising" ⇒ true
@@ -201,10 +201,10 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
new TestKit(appLifecycle) {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
within(3 seconds) {
- val supervisor = TestActorRef[TestLogActor](Props[TestLogActor])
- val sclass = classOf[TestLogActor]
- val actor = TestActorRef[TestLogActor](Props[TestLogActor], supervisor, "none")
- val aname = actor.path.toString
+ val supervisor: akka.testkit.TestActorRef[akka.event.LoggingReceiveSpec.TestLogActor] = TestActorRef[TestLogActor](Props[TestLogActor])
+ val sclass: Class[akka.event.LoggingReceiveSpec.TestLogActor] = classOf[TestLogActor]
+ val actor: akka.testkit.TestActorRef[akka.event.LoggingReceiveSpec.TestLogActor] = TestActorRef[TestLogActor](Props[TestLogActor], supervisor, "none")
+ val aname: String = actor.path.toString
supervisor watch actor
fishForMessage(hint = "now watched by") {
@@ -226,18 +226,18 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
system.eventStream.subscribe(testActor, classOf[Logging.Debug])
system.eventStream.subscribe(testActor, classOf[Logging.Error])
within(3 seconds) {
- val supervisor = TestActorRef[TestLogActor](Props[TestLogActor])
- val sname = supervisor.path.toString
- val sclass = classOf[TestLogActor]
+ val supervisor: akka.testkit.TestActorRef[akka.event.LoggingReceiveSpec.TestLogActor] = TestActorRef[TestLogActor](Props[TestLogActor])
+ val sname: String = supervisor.path.toString
+ val sclass: Class[akka.event.LoggingReceiveSpec.TestLogActor] = classOf[TestLogActor]
expectMsgAllPF(messages = 2) {
case Logging.Debug(`sname`, `sclass`, msg: String) if msg startsWith "started" ⇒ 0
case Logging.Debug(_, _, msg: String) if msg startsWith "now supervising" ⇒ 1
}
- val actor = TestActorRef[TestLogActor](Props[TestLogActor], supervisor, "none")
- val aname = actor.path.toString
- val aclass = classOf[TestLogActor]
+ val actor: akka.testkit.TestActorRef[akka.event.LoggingReceiveSpec.TestLogActor] = TestActorRef[TestLogActor](Props[TestLogActor], supervisor, "none")
+ val aname: String = actor.path.toString
+ val aclass: Class[akka.event.LoggingReceiveSpec.TestLogActor] = classOf[TestLogActor]
expectMsgAllPF(messages = 2) {
case Logging.Debug(`aname`, `aclass`, msg: String) if msg.startsWith("started (" + classOf[TestLogActor].getName) ⇒ 0
@@ -261,20 +261,20 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
}
def expectMsgAllPF(messages: Int)(matchers: PartialFunction[AnyRef, Int]): Set[Int] = {
- val max = remainingOrDefault
+ val max: scala.concurrent.duration.FiniteDuration = remainingOrDefault
@tailrec def receiveNMatching(gotMatching: Set[Int], unknown: Vector[Any]): Set[Int] = {
if (unknown.size >= 20)
throw new IllegalStateException(s"Got too many unknown messages: [${unknown.mkString(", ")}]")
else if (gotMatching.size == messages) gotMatching
else {
- val msg = receiveOne(remainingOrDefault)
+ val msg: AnyRef = receiveOne(remainingOrDefault)
assert(msg ne null, s"timeout ($max) during expectMsgAllPF, got matching " +
s"[${gotMatching.mkString(", ")}], got unknown: [${unknown.mkString(", ")}]")
if (matchers.isDefinedAt(msg)) receiveNMatching(gotMatching + matchers(msg), Vector.empty)
else receiveNMatching(gotMatching, unknown :+ msg) // unknown message, just ignore
}
}
- val set = receiveNMatching(Set.empty, Vector.empty)
+ val set: Set[Int] = receiveNMatching(Set.empty, Vector.empty)
assert(set == (0 until messages).toSet)
set
}
diff --git a/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala b/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala
index 4c5c9bb..acc3f05 100644
--- a/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala
@@ -5,14 +5,14 @@ import akka.testkit._
class MarkerLoggingSpec extends AkkaSpec with ImplicitSender {
"A MarkerLoggerAdapter" should {
- val markerLogging = new MarkerLoggingAdapter(system.eventStream, getClass.getName, this.getClass, new DefaultLoggingFilter(() ⇒ Logging.InfoLevel))
+ val markerLogging: akka.event.MarkerLoggingAdapter = new MarkerLoggingAdapter(system.eventStream, getClass.getName, this.getClass, new DefaultLoggingFilter(() ⇒ Logging.InfoLevel))
"add markers to logging" in {
system.eventStream.subscribe(self, classOf[Info])
system.eventStream.publish(TestEvent.Mute(EventFilter.info()))
markerLogging.info(LogMarker.Security, "This is a security problem")
- val info = expectMsgType[Info3]
+ val info: akka.event.Logging.Info3 = expectMsgType[Info3]
info.message should be("This is a security problem")
info.marker.name should be("SECURITY")
}
diff --git a/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala b/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala
index fcdd1bf..cf11bdf 100644
--- a/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala
@@ -11,7 +11,7 @@ import scala.util.control.NoStackTrace
object JavaLoggerSpec {
- val config = ConfigFactory.parseString("""
+ val config: com.typesafe.config.Config = ConfigFactory.parseString("""
akka {
loglevel = INFO
loggers = ["akka.event.jul.JavaLogger"]
@@ -19,7 +19,7 @@ object JavaLoggerSpec {
}""")
class LogProducer extends Actor with ActorLogging {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case e: Exception ⇒
log.error(e, e.getMessage)
case (s: String, x: Int) ⇒
@@ -32,7 +32,7 @@ object JavaLoggerSpec {
class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
- val logger = logging.Logger.getLogger(classOf[JavaLoggerSpec.LogProducer].getName)
+ val logger: java.util.logging.Logger = logging.Logger.getLogger(classOf[JavaLoggerSpec.LogProducer].getName)
logger.setUseParentHandlers(false) // turn off output of test LogRecords
logger.addHandler(new logging.Handler {
def publish(record: logging.LogRecord) {
@@ -43,14 +43,14 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
def close() {}
})
- val producer = system.actorOf(Props[JavaLoggerSpec.LogProducer], name = "log")
+ val producer: akka.actor.ActorRef = system.actorOf(Props[JavaLoggerSpec.LogProducer], name = "log")
"JavaLogger" must {
"log error with stackTrace" in {
producer ! new JavaLoggerSpec.SimulatedExc
- val record = expectMsgType[logging.LogRecord]
+ val record: java.util.logging.LogRecord = expectMsgType[logging.LogRecord]
record should not be (null)
record.getMillis should not be (0)
@@ -65,7 +65,7 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
"log info without stackTrace" in {
producer ! (("{} is the magic number", 3))
- val record = expectMsgType[logging.LogRecord]
+ val record: java.util.logging.LogRecord = expectMsgType[logging.LogRecord]
record should not be (null)
record.getMillis should not be (0)
diff --git a/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala b/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala
index 82c8574..1815f0b 100644
--- a/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala
@@ -22,18 +22,18 @@ class CapacityLimitSpec extends AkkaSpec("""
// we now have three channels registered: a listener, a server connection and a client connection
// so register one more channel
- val commander = TestProbe()
- val addresses = temporaryServerAddresses(2)
+ val commander: akka.testkit.TestProbe = TestProbe()
+ val addresses: scala.collection.immutable.IndexedSeq[java.net.InetSocketAddress] = temporaryServerAddresses(2)
commander.send(IO(Tcp), Bind(bindHandler.ref, addresses(0)))
commander.expectMsg(Bound(addresses(0)))
// we are now at the configured max-channel capacity of 4
- val bindToFail = Bind(bindHandler.ref, addresses(1))
+ val bindToFail: akka.io.Tcp.Bind = Bind(bindHandler.ref, addresses(1))
commander.send(IO(Tcp), bindToFail)
commander.expectMsgType[CommandFailed].cmd should be theSameInstanceAs (bindToFail)
- val connectToFail = Connect(endpoint)
+ val connectToFail: akka.io.Tcp.Connect = Connect(endpoint)
commander.send(IO(Tcp), connectToFail)
commander.expectMsgType[CommandFailed].cmd should be theSameInstanceAs (connectToFail)
}
diff --git a/akka-actor-tests/src/test/scala/akka/io/SimpleDnsCacheSpec.scala b/akka-actor-tests/src/test/scala/akka/io/SimpleDnsCacheSpec.scala
index b45f547..e6bae7b 100644
--- a/akka-actor-tests/src/test/scala/akka/io/SimpleDnsCacheSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/SimpleDnsCacheSpec.scala
@@ -8,11 +8,11 @@ import org.scalatest.{ Matchers, WordSpec }
class SimpleDnsCacheSpec extends WordSpec with Matchers {
"Cache" should {
"not reply with expired but not yet swept out entries" in {
- val localClock = new AtomicLong(0)
+ val localClock: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
val cache: SimpleDnsCache = new SimpleDnsCache() {
- override protected def clock() = localClock.get
+ override protected def clock(): Long = localClock.get
}
- val cacheEntry = Dns.Resolved("test.local", Seq(InetAddress.getByName("127.0.0.1")))
+ val cacheEntry: akka.io.Dns.Resolved = Dns.Resolved("test.local", Seq(InetAddress.getByName("127.0.0.1")))
cache.put(cacheEntry, 5000)
cache.cached("test.local") should ===(Some(cacheEntry))
@@ -23,11 +23,11 @@ class SimpleDnsCacheSpec extends WordSpec with Matchers {
}
"sweep out expired entries on cleanup()" in {
- val localClock = new AtomicLong(0)
+ val localClock: java.util.concurrent.atomic.AtomicLong = new AtomicLong(0)
val cache: SimpleDnsCache = new SimpleDnsCache() {
- override protected def clock() = localClock.get
+ override protected def clock(): Long = localClock.get
}
- val cacheEntry = Dns.Resolved("test.local", Seq(InetAddress.getByName("127.0.0.1")))
+ val cacheEntry: akka.io.Dns.Resolved = Dns.Resolved("test.local", Seq(InetAddress.getByName("127.0.0.1")))
cache.put(cacheEntry, 5000)
cache.cached("test.local") should ===(Some(cacheEntry))
diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala
index 6b90705..77fa869 100644
--- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala
@@ -48,11 +48,11 @@ class TcpConnectionSpec extends AkkaSpec("""
}
lazy val ConnectionResetByPeerMessage: String = {
- val serverSocket = ServerSocketChannel.open()
+ val serverSocket: java.nio.channels.ServerSocketChannel = ServerSocketChannel.open()
serverSocket.socket.bind(new InetSocketAddress("127.0.0.1", 0))
try {
- val clientSocket = SocketChannel.open(new InetSocketAddress("127.0.0.1", serverSocket.socket().getLocalPort))
- val clientSocketOnServer = acceptServerSideConnection(serverSocket)
+ val clientSocket: java.nio.channels.SocketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", serverSocket.socket().getLocalPort))
+ val clientSocketOnServer: java.nio.channels.SocketChannel = acceptServerSideConnection(serverSocket)
clientSocketOnServer.socket.setSoLinger(true, 0)
clientSocketOnServer.close()
clientSocket.read(ByteBuffer.allocate(1))
@@ -63,11 +63,11 @@ class TcpConnectionSpec extends AkkaSpec("""
}
lazy val ConnectionRefusedMessagePrefix: String = {
- val serverSocket = ServerSocketChannel.open()
+ val serverSocket: java.nio.channels.ServerSocketChannel = ServerSocketChannel.open()
serverSocket.socket.bind(new InetSocketAddress("127.0.0.1", 0))
try {
serverSocket.close()
- val clientSocket = SocketChannel.open(new InetSocketAddress("127.0.0.1", serverSocket.socket().getLocalPort))
+ val clientSocket: java.nio.channels.SocketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", serverSocket.socket().getLocalPort))
clientSocket.finishConnect()
clientSocket.write(ByteBuffer.allocate(1))
null
@@ -83,8 +83,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"set socket options before connecting" in new LocalServerTest() {
run {
- val connectionActor = createConnectionActor(options = Vector(Inet.SO.ReuseAddress(true)))
- val clientChannel = connectionActor.underlyingActor.channel
+ val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActor(options = Vector(Inet.SO.ReuseAddress(true)))
+ val clientChannel: java.nio.channels.SocketChannel = connectionActor.underlyingActor.channel
clientChannel.socket.getReuseAddress should ===(true)
}
}
@@ -92,8 +92,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"set socket options after connecting" ignore new LocalServerTest() {
run {
// Workaround for systems where SO_KEEPALIVE is true by default
- val connectionActor = createConnectionActor(options = Vector(SO.KeepAlive(false)))
- val clientChannel = connectionActor.underlyingActor.channel
+ val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActor(options = Vector(SO.KeepAlive(false)))
+ val clientChannel: java.nio.channels.SocketChannel = connectionActor.underlyingActor.channel
clientChannel.socket.getKeepAlive should ===(true) // only set after connection is established
EventFilter.warning(pattern = "registration timeout", occurrences = 1) intercept {
selector.send(connectionActor, ChannelConnectable)
@@ -118,15 +118,15 @@ class TcpConnectionSpec extends AkkaSpec("""
"forward incoming data as Received messages instantly as long as more data is available" in
new EstablishedConnectionTest() { // to make sure enough data gets through
- override lazy val connectionActor = createConnectionActor(options = List(Inet.SO.ReceiveBufferSize(1000000)))
+ override lazy val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActor(options = List(Inet.SO.ReceiveBufferSize(1000000)))
run {
- val bufferSize = Tcp(system).Settings.DirectBufferSize
- val DataSize = bufferSize + 1500
- val bigData = new Array[Byte](DataSize)
- val buffer = ByteBuffer.wrap(bigData)
+ val bufferSize: Int = Tcp(system).Settings.DirectBufferSize
+ val DataSize: Int = bufferSize + 1500
+ val bigData: Array[Byte] = new Array[Byte](DataSize)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.wrap(bigData)
serverSideChannel.socket.setSendBufferSize(150000)
- val wrote = serverSideChannel.write(buffer)
+ val wrote: Int = serverSideChannel.write(buffer)
wrote should ===(DataSize)
expectNoMsg(1000.millis) // data should have been transferred fully by now
@@ -140,7 +140,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"receive data directly when the connection is established" in new UnacceptedConnectionTest() {
run {
- val serverSideChannel = acceptServerSideConnection(localServerChannel)
+ val serverSideChannel: java.nio.channels.SocketChannel = acceptServerSideConnection(localServerChannel)
serverSideChannel.write(ByteBuffer.wrap("immediatedata".getBytes("ASCII")))
serverSideChannel.configureBlocking(false)
@@ -158,11 +158,11 @@ class TcpConnectionSpec extends AkkaSpec("""
"write data to network (and acknowledge)" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
// reply to write commander with Ack
- val ackedWrite = Write(ByteString("testdata"), Ack)
- val buffer = ByteBuffer.allocate(100)
+ val ackedWrite: akka.io.Tcp.Write = Write(ByteString("testdata"), Ack)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(100)
serverSideChannel.read(buffer) should ===(0)
writer.send(connectionActor, ackedWrite)
writer.expectMsg(Ack)
@@ -171,7 +171,7 @@ class TcpConnectionSpec extends AkkaSpec("""
buffer.limit should ===(8)
// not reply to write commander for writes without Ack
- val unackedWrite = Write(ByteString("morestuff!"))
+ val unackedWrite: akka.io.Tcp.Write = Write(ByteString("morestuff!"))
buffer.clear()
serverSideChannel.read(buffer) should ===(0)
writer.send(connectionActor, unackedWrite)
@@ -184,16 +184,16 @@ class TcpConnectionSpec extends AkkaSpec("""
"send big buffers to network correctly" in new EstablishedConnectionTest() {
run {
- val bufferSize = 512 * 1024 // 256kB are too few
- val random = new Random(0)
- val testBytes = new Array[Byte](bufferSize)
+ val bufferSize: Int = 512 * 1024 // 256kB are too few
+ val random: java.util.Random = new Random(0)
+ val testBytes: Array[Byte] = new Array[Byte](bufferSize)
random.nextBytes(testBytes)
- val testData = ByteString(testBytes)
+ val testData: akka.util.ByteString = ByteString(testBytes)
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
- val write = Write(testData, Ack)
- val buffer = ByteBuffer.allocate(bufferSize)
+ val write: akka.io.Tcp.Write = Write(testData, Ack)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(bufferSize)
serverSideChannel.read(buffer) should ===(0)
writer.send(connectionActor, write)
pullFromServerSide(remaining = bufferSize, into = buffer)
@@ -206,7 +206,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"write data after not acknowledged data" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
writer.send(connectionActor, Write(ByteString(42.toByte)))
writer.expectNoMsg(500.millis)
}
@@ -214,7 +214,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"acknowledge the completion of an ACKed empty write" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
writer.send(connectionActor, Write(ByteString.empty, Ack))
writer.expectMsg(Ack)
}
@@ -222,7 +222,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"not acknowledge the completion of a NACKed empty write" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
writer.send(connectionActor, Write(ByteString.empty, NoAck))
writer.expectNoMsg(250.millis)
writer.send(connectionActor, Write(ByteString.empty, NoAck(42)))
@@ -233,7 +233,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"write file to network" in new EstablishedConnectionTest() {
run {
// hacky: we need a file for testing purposes, so try to get the biggest one from our own classpath
- val testFile =
+ val testFile: java.io.File =
classOf[TcpConnectionSpec].getClassLoader.asInstanceOf[URLClassLoader]
.getURLs
.filter(_.getProtocol == "file")
@@ -243,9 +243,9 @@ class TcpConnectionSpec extends AkkaSpec("""
.head
// maximum of 100 MB
- val size = math.min(testFile.length(), 100000000).toInt
+ val size: Int = math.min(testFile.length(), 100000000).toInt
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
writer.send(connectionActor, WriteFile(testFile.getAbsolutePath, 0, size, Ack))
pullFromServerSide(size, 1000000)
writer.expectMsg(Ack)
@@ -254,15 +254,15 @@ class TcpConnectionSpec extends AkkaSpec("""
"write a CompoundWrite to the network and produce correct ACKs" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
- val compoundWrite =
+ val writer: akka.testkit.TestProbe = TestProbe()
+ val compoundWrite: akka.io.Tcp.CompoundWrite =
Write(ByteString("test1"), Ack(1)) +:
Write(ByteString("test2")) +:
Write(ByteString.empty, Ack(3)) +:
Write(ByteString("test4"), Ack(4))
// reply to write commander with Ack
- val buffer = ByteBuffer.allocate(100)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(100)
serverSideChannel.read(buffer) should ===(0)
writer.send(connectionActor, compoundWrite)
@@ -289,7 +289,7 @@ class TcpConnectionSpec extends AkkaSpec("""
*/
"stop writing in cases of backpressure and resume afterwards" in
new EstablishedConnectionTest() {
- override lazy val connectionActor = createConnectionActor(options = List(Inet.SO.ReceiveBufferSize(1000000)))
+ override lazy val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActor(options = List(Inet.SO.ReceiveBufferSize(1000000)))
run {
info("Currently ignored as SO_SNDBUF is usually a lower bound on the send buffer so the test fails as no real " +
"backpressure present.")
@@ -302,11 +302,11 @@ class TcpConnectionSpec extends AkkaSpec("""
awaitCond(clientSideChannel.socket.getSendBufferSize == 1024)
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
// producing backpressure by sending much more than currently fits into
// our send buffer
- val firstWrite = writeCmd(Ack1)
+ val firstWrite: akka.io.Tcp.Write = writeCmd(Ack1)
// try to write the buffer but since the SO_SNDBUF is too small
// it will have to keep the rest of the piece and send it
@@ -316,7 +316,7 @@ class TcpConnectionSpec extends AkkaSpec("""
// send another write which should fail immediately
// because we don't store more than one piece in flight
- val secondWrite = writeCmd(Ack2)
+ val secondWrite: akka.io.Tcp.Write = writeCmd(Ack2)
writer.send(connectionActor, secondWrite)
writer.expectMsg(CommandFailed(secondWrite))
@@ -362,15 +362,15 @@ class TcpConnectionSpec extends AkkaSpec("""
"respect pull mode" in new EstablishedConnectionTest(pullMode = true) {
// override config to decrease default buffer size
- def config =
+ def config: com.typesafe.config.Config =
ConfigFactory.parseString("akka.io.tcp.direct-buffer-size = 1k")
.withFallback(AkkaSpec.testConf)
override implicit lazy val system: ActorSystem = ActorSystem("respectPullModeTest", config)
try run {
- val maxBufferSize = 1 * 1024
- val ts = "t" * maxBufferSize
- val us = "u" * (maxBufferSize / 2)
+ val maxBufferSize: Int = 1 * 1024
+ val ts: String = "t" * maxBufferSize
+ val us: String = "u" * (maxBufferSize / 2)
// send a batch that is bigger than the default buffer to make sure we don't recurse and
// send more than one Received messages
@@ -394,7 +394,7 @@ class TcpConnectionSpec extends AkkaSpec("""
interestCallReceiver.expectNoMsg(100.millis)
connectionHandler.expectNoMsg(100.millis)
- val vs = "v" * (maxBufferSize / 2)
+ val vs: String = "v" * (maxBufferSize / 2)
serverSideChannel.write(ByteBuffer.wrap(vs.getBytes("ASCII")))
connectionActor ! ResumeReading
@@ -417,7 +417,7 @@ class TcpConnectionSpec extends AkkaSpec("""
// we send a write and a close command directly afterwards
connectionHandler.send(connectionActor, writeCmd(Ack))
- val closeCommander = TestProbe()
+ val closeCommander: akka.testkit.TestProbe = TestProbe()
closeCommander.send(connectionActor, Close)
pullFromServerSide(TestSize)
@@ -428,7 +428,7 @@ class TcpConnectionSpec extends AkkaSpec("""
serverSelectionKey should be(selectedAs(OP_READ, 2.seconds))
- val buffer = ByteBuffer.allocate(1)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(1)
serverSideChannel.read(buffer) should ===(-1)
}
}
@@ -450,8 +450,8 @@ class TcpConnectionSpec extends AkkaSpec("""
assertThisConnectionActorTerminated()
- val buffer = ByteBuffer.allocate(1)
- val thrown = the[IOException] thrownBy {
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(1)
+ val thrown: java.io.IOException = the[IOException] thrownBy {
windowsWorkaroundToDetectAbort()
serverSideChannel.read(buffer)
}
@@ -489,7 +489,7 @@ class TcpConnectionSpec extends AkkaSpec("""
selector.send(connectionActor, ChannelReadable)
- val buffer = ByteBuffer.allocate(1)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(1)
serverSelectionKey should be(selectedAs(OP_READ, 2.seconds))
serverSideChannel.read(buffer) should ===(-1)
@@ -524,7 +524,7 @@ class TcpConnectionSpec extends AkkaSpec("""
selector.send(connectionActor, ChannelReadable)
connectionHandler.expectNoMsg(100.millis) // not yet
- val buffer = ByteBuffer.allocate(1)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(1)
serverSelectionKey should be(selectedAs(SelectionKey.OP_READ, 2.seconds))
serverSideChannel.read(buffer) should ===(-1)
@@ -588,7 +588,7 @@ class TcpConnectionSpec extends AkkaSpec("""
run {
abortClose(serverSideChannel)
selector.send(connectionActor, ChannelReadable)
- val err = connectionHandler.expectMsgType[ErrorClosed]
+ val err: akka.io.Tcp.ErrorClosed = connectionHandler.expectMsgType[ErrorClosed]
err.cause should ===(ConnectionResetByPeerMessage)
// wait a while
@@ -600,7 +600,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"report when peer closed the connection when trying to write" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
+ val writer: akka.testkit.TestProbe = TestProbe()
abortClose(serverSideChannel)
writer.send(connectionActor, Write(ByteString("testdata")))
@@ -612,20 +612,20 @@ class TcpConnectionSpec extends AkkaSpec("""
}
}
- val UnboundAddress = temporaryServerAddress()
+ val UnboundAddress: java.net.InetSocketAddress = temporaryServerAddress()
"report failed connection attempt when target is unreachable" in
new UnacceptedConnectionTest() {
- override lazy val connectionActor = createConnectionActor(serverAddress = UnboundAddress)
+ override lazy val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActor(serverAddress = UnboundAddress)
run {
- val sel = SelectorProvider.provider().openSelector()
+ val sel: java.nio.channels.spi.AbstractSelector = SelectorProvider.provider().openSelector()
try {
- val key = clientSideChannel.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ)
+ val key: java.nio.channels.SelectionKey = clientSideChannel.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ)
// This timeout should be large enough to work on Windows
sel.select(3000)
key.isConnectable should ===(true)
- val forceThisLazyVal = connectionActor.toString
+ val forceThisLazyVal: String = connectionActor.toString
Thread.sleep(300)
selector.send(connectionActor, ChannelConnectable)
userHandler.expectMsg(CommandFailed(Connect(UnboundAddress)))
@@ -638,8 +638,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"report failed connection attempt when target cannot be resolved" in
new UnacceptedConnectionTest() {
- val address = new InetSocketAddress("notthere.local", 666)
- override lazy val connectionActor = createConnectionActorWithoutRegistration(serverAddress = address)
+ val address: java.net.InetSocketAddress = new InetSocketAddress("notthere.local", 666)
+ override lazy val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActorWithoutRegistration(serverAddress = address)
run {
connectionActor ! newChannelRegistration
userHandler.expectMsg(30.seconds, CommandFailed(Connect(address)))
@@ -648,7 +648,7 @@ class TcpConnectionSpec extends AkkaSpec("""
"report failed connection attempt when timing out" in
new UnacceptedConnectionTest() {
- override lazy val connectionActor = createConnectionActor(serverAddress = UnboundAddress, timeout = Option(100.millis))
+ override lazy val connectionActor: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActor(serverAddress = UnboundAddress, timeout = Option(100.millis))
run {
connectionActor.toString should not be ("")
userHandler.expectMsg(CommandFailed(Connect(UnboundAddress, timeout = Option(100.millis))))
@@ -686,7 +686,7 @@ class TcpConnectionSpec extends AkkaSpec("""
watch(connectionActor)
EventFilter[DeathPactException](occurrences = 1) intercept {
system.stop(connectionHandler.ref)
- val deaths = Set(expectMsgType[Terminated].actor, expectMsgType[Terminated].actor)
+ val deaths: scala.collection.immutable.Set[akka.actor.ActorRef] = Set(expectMsgType[Terminated].actor, expectMsgType[Terminated].actor)
deaths should ===(Set(connectionHandler.ref, connectionActor))
}
}
@@ -694,8 +694,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"support ResumeWriting (backed up)" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
- val write = writeCmd(NoAck)
+ val writer: akka.testkit.TestProbe = TestProbe()
+ val write: akka.io.Tcp.Write = writeCmd(NoAck)
// fill up the write buffer until NACK
var written = 0
@@ -732,8 +732,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"support ResumeWriting (queue flushed)" in new EstablishedConnectionTest() {
run {
- val writer = TestProbe()
- val write = writeCmd(NoAck)
+ val writer: akka.testkit.TestProbe = TestProbe()
+ val write: akka.io.Tcp.Write = writeCmd(NoAck)
// fill up the write buffer until NACK
var written = 0
@@ -768,8 +768,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"support useResumeWriting==false (backed up)" in new EstablishedConnectionTest(useResumeWriting = false) {
run {
- val writer = TestProbe()
- val write = writeCmd(NoAck)
+ val writer: akka.testkit.TestProbe = TestProbe()
+ val write: akka.io.Tcp.Write = writeCmd(NoAck)
// fill up the write buffer until NACK
var written = 0
@@ -801,8 +801,8 @@ class TcpConnectionSpec extends AkkaSpec("""
"support useResumeWriting==false (queue flushed)" in new EstablishedConnectionTest(useResumeWriting = false) {
run {
- val writer = TestProbe()
- val write = writeCmd(NoAck)
+ val writer: akka.testkit.TestProbe = TestProbe()
+ val write: akka.io.Tcp.Write = writeCmd(NoAck)
// fill up the write buffer until NACK
var written = 0
@@ -828,10 +828,10 @@ class TcpConnectionSpec extends AkkaSpec("""
"report abort before handler is registered (reproducer from #15033)" in {
// This test needs the OP_CONNECT workaround on Windows, see original report #15033 and parent ticket #15766
- val port = SocketUtil.temporaryServerAddress().getPort
- val bindAddress = new InetSocketAddress(port)
- val serverSocket = new ServerSocket(bindAddress.getPort, 100, bindAddress.getAddress)
- val connectionProbe = TestProbe()
+ val port: Int = SocketUtil.temporaryServerAddress().getPort
+ val bindAddress: java.net.InetSocketAddress = new InetSocketAddress(port)
+ val serverSocket: java.net.ServerSocket = new ServerSocket(bindAddress.getPort, 100, bindAddress.getAddress)
+ val connectionProbe: akka.testkit.TestProbe = TestProbe()
connectionProbe.send(IO(Tcp), Connect(bindAddress))
@@ -839,9 +839,9 @@ class TcpConnectionSpec extends AkkaSpec("""
try {
serverSocket.setSoTimeout(remainingOrDefault.toMillis.toInt)
- val socket = serverSocket.accept()
+ val socket: java.net.Socket = serverSocket.accept()
connectionProbe.expectMsgType[Tcp.Connected]
- val connectionActor = connectionProbe.sender()
+ val connectionActor: akka.actor.ActorRef = connectionProbe.sender()
connectionActor ! PoisonPill
watch(connectionActor)
expectTerminated(connectionActor)
@@ -870,13 +870,13 @@ class TcpConnectionSpec extends AkkaSpec("""
/** Allows overriding the system used */
implicit def system: ActorSystem = thisSpecs.system
- val serverAddress = temporaryServerAddress()
- val localServerChannel = ServerSocketChannel.open()
- val userHandler = TestProbe()
- val selector = TestProbe()
+ val serverAddress: java.net.InetSocketAddress = temporaryServerAddress()
+ val localServerChannel: java.nio.channels.ServerSocketChannel = ServerSocketChannel.open()
+ val userHandler: akka.testkit.TestProbe = TestProbe()
+ val selector: akka.testkit.TestProbe = TestProbe()
- var registerCallReceiver = TestProbe()
- var interestCallReceiver = TestProbe()
+ var registerCallReceiver: akka.testkit.TestProbe = TestProbe()
+ var interestCallReceiver: akka.testkit.TestProbe = TestProbe()
def ignoreWindowsWorkaroundForTicket15766(): Unit = {
// Due to the Windows workaround of #15766 we need to set an OP_CONNECT to reliably detect connection resets
@@ -902,7 +902,7 @@ class TcpConnectionSpec extends AkkaSpec("""
options: immutable.Seq[SocketOption] = Nil,
timeout: Option[FiniteDuration] = None,
pullMode: Boolean = false): TestActorRef[TcpOutgoingConnection] = {
- val ref = createConnectionActorWithoutRegistration(serverAddress, options, timeout, pullMode)
+ val ref: akka.testkit.TestActorRef[akka.io.TcpOutgoingConnection] = createConnectionActorWithoutRegistration(serverAddress, options, timeout, pullMode)
ref ! newChannelRegistration
ref
}
@@ -934,7 +934,7 @@ class TcpConnectionSpec extends AkkaSpec("""
// lazy init since potential exceptions should not be triggered in the constructor but during execution of `run`
private[io] lazy val connectionActor = createConnectionActor(serverAddress, pullMode = pullMode)
// calling .underlyingActor ensures that the actor is actually created at this point
- lazy val clientSideChannel = connectionActor.underlyingActor.channel
+ lazy val clientSideChannel: java.nio.channels.SocketChannel = connectionActor.underlyingActor.channel
override def run(body: ⇒ Unit): Unit = super.run {
registerCallReceiver.expectMsg(Registration(clientSideChannel, 0))
@@ -950,12 +950,12 @@ class TcpConnectionSpec extends AkkaSpec("""
extends UnacceptedConnectionTest(pullMode) {
// lazy init since potential exceptions should not be triggered in the constructor but during execution of `run`
- lazy val serverSideChannel = acceptServerSideConnection(localServerChannel)
- lazy val connectionHandler = TestProbe()
- lazy val nioSelector = SelectorProvider.provider().openSelector()
- lazy val clientSelectionKey = registerChannel(clientSideChannel, "client")
- lazy val serverSelectionKey = registerChannel(serverSideChannel, "server")
- lazy val defaultbuffer = ByteBuffer.allocate(TestSize)
+ lazy val serverSideChannel: java.nio.channels.SocketChannel = acceptServerSideConnection(localServerChannel)
+ lazy val connectionHandler: akka.testkit.TestProbe = TestProbe()
+ lazy val nioSelector: java.nio.channels.spi.AbstractSelector = SelectorProvider.provider().openSelector()
+ lazy val clientSelectionKey: java.nio.channels.SelectionKey = registerChannel(clientSideChannel, "client")
+ lazy val serverSelectionKey: java.nio.channels.SelectionKey = registerChannel(serverSideChannel, "server")
+ lazy val defaultbuffer: java.nio.ByteBuffer = ByteBuffer.allocate(TestSize)
def windowsWorkaroundToDetectAbort(): Unit = {
// Due to a Windows quirk we need to set an OP_CONNECT to reliably detect connection resets, see #1576
@@ -994,7 +994,7 @@ class TcpConnectionSpec extends AkkaSpec("""
final val TestSize = 10000 // compile-time constant
- def writeCmd(ack: Event) =
+ def writeCmd(ack: Event): akka.io.Tcp.Write =
Write(ByteString(Array.fill[Byte](TestSize)(0)), ack)
def closeServerSideAndWaitForClientReadable(fullClose: Boolean = true): Unit = {
@@ -1003,7 +1003,7 @@ class TcpConnectionSpec extends AkkaSpec("""
}
def registerChannel(channel: SocketChannel, name: String): SelectionKey = {
- val res = channel.register(nioSelector, 0)
+ val res: java.nio.channels.SelectionKey = channel.register(nioSelector, 0)
res.attach(name)
res
}
@@ -1012,7 +1012,7 @@ class TcpConnectionSpec extends AkkaSpec("""
if (key.isValid) {
key.interestOps(interest)
nioSelector.selectedKeys().clear()
- val ret = nioSelector.select(millis)
+ val ret: Int = nioSelector.select(millis)
key.interestOps(0)
ret > 0 && nioSelector.selectedKeys().contains(key) && key.isValid &&
@@ -1020,8 +1020,8 @@ class TcpConnectionSpec extends AkkaSpec("""
} else false
def openSelectorFor(channel: SocketChannel, interests: Int): (Selector, SelectionKey) = {
- val sel = SelectorProvider.provider().openSelector()
- val key = channel.register(sel, interests)
+ val sel: java.nio.channels.spi.AbstractSelector = SelectorProvider.provider().openSelector()
+ val key: java.nio.channels.SelectionKey = channel.register(sel, interests)
(sel, key)
}
@@ -1045,7 +1045,7 @@ class TcpConnectionSpec extends AkkaSpec("""
selector.send(connectionActor, ChannelWritable)
}
- val read =
+ val read: Int =
if (nioSelector.selectedKeys().contains(serverSelectionKey)) {
if (into eq defaultbuffer) into.clear()
serverSideChannel.read(into) match {
@@ -1065,8 +1065,8 @@ class TcpConnectionSpec extends AkkaSpec("""
selector.send(connectionActor, ChannelReadable)
- val gotReceived = connectionHandler.expectMsgType[Received]
- val receivedString = gotReceived.data.decodeString("ASCII")
+ val gotReceived: akka.io.Tcp.Received = connectionHandler.expectMsgType[Received]
+ val receivedString: String = gotReceived.data.decodeString("ASCII")
data.startsWith(receivedString) should ===(true)
if (receivedString.length < data.length)
expectReceivedString(data.drop(receivedString.length))
@@ -1080,14 +1080,14 @@ class TcpConnectionSpec extends AkkaSpec("""
def selectedAs(interest: Int, duration: Duration): BeMatcher[SelectionKey] =
new BeMatcher[SelectionKey] {
- def apply(key: SelectionKey) =
+ def apply(key: SelectionKey): org.scalatest.matchers.MatchResult =
MatchResult(
checkFor(key, interest, duration.toMillis.toInt),
"%s key was not selected for %s after %s" format (key.attachment(), interestsDesc(interest), duration),
"%s key was selected for %s after %s" format (key.attachment(), interestsDesc(interest), duration))
}
- val interestsNames =
+ val interestsNames: Seq[(Int, String)] =
Seq(OP_ACCEPT → "accepting", OP_CONNECT → "connecting", OP_READ → "reading", OP_WRITE → "writing")
def interestsDesc(interests: Int): String =
interestsNames.filter(i ⇒ (i._1 & interests) != 0).map(_._2).mkString(", ")
diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala
index 3311c12..94f9780 100644
--- a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala
@@ -150,28 +150,28 @@ class TcpIntegrationSpec extends AkkaSpec("""
expectReceivedData(clientHandler, 100000)
- override def bindOptions = List(SO.SendBufferSize(1024))
- override def connectOptions = List(SO.ReceiveBufferSize(1024))
+ override def bindOptions: List[akka.io.Inet.SO.SendBufferSize] = List(SO.SendBufferSize(1024))
+ override def connectOptions: List[akka.io.Inet.SO.ReceiveBufferSize] = List(SO.ReceiveBufferSize(1024))
}
"don't report Connected when endpoint isn't responding" in {
- val connectCommander = TestProbe()
+ val connectCommander: akka.testkit.TestProbe = TestProbe()
// a "random" endpoint hopefully unavailable since it's in the test-net IP range
- val endpoint = new InetSocketAddress("192.0.2.1", 23825)
+ val endpoint: java.net.InetSocketAddress = new InetSocketAddress("192.0.2.1", 23825)
connectCommander.send(IO(Tcp), Connect(endpoint))
// expecting CommandFailed or no reply (within timeout)
- val replies = connectCommander.receiveWhile(1.second) { case m: Connected ⇒ m }
+ val replies: scala.collection.immutable.Seq[akka.io.Tcp.Connected] = connectCommander.receiveWhile(1.second) { case m: Connected ⇒ m }
replies should ===(Nil)
}
"handle tcp connection actor death properly" in new TestSetup(shouldBindServer = false) {
- val serverSocket = new ServerSocket(endpoint.getPort(), 100, endpoint.getAddress())
- val connectCommander = TestProbe()
+ val serverSocket: java.net.ServerSocket = new ServerSocket(endpoint.getPort(), 100, endpoint.getAddress())
+ val connectCommander: akka.testkit.TestProbe = TestProbe()
connectCommander.send(IO(Tcp), Connect(endpoint))
- val accept = serverSocket.accept()
+ val accept: java.net.Socket = serverSocket.accept()
connectCommander.expectMsgType[Connected].remoteAddress should ===(endpoint)
- val connectionActor = connectCommander.lastSender
+ val connectionActor: akka.actor.ActorRef = connectCommander.lastSender
connectCommander.send(connectionActor, PoisonPill)
failAfter(3 seconds) {
try {
@@ -189,9 +189,9 @@ class TcpIntegrationSpec extends AkkaSpec("""
clientConnection: ActorRef,
serverHandler: TestProbe,
serverConnection: ActorRef,
- rounds: Int = 100) = {
+ rounds: Int = 100): Unit = {
- val testData = ByteString(0)
+ val testData: akka.util.ByteString = ByteString(0)
(1 to rounds) foreach { _ ⇒
clientHandler.send(clientConnection, Write(testData))
serverHandler.expectMsg(Received(testData))
diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala
index 46d3cb1..366d608 100644
--- a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala
@@ -15,26 +15,26 @@ import Tcp._
trait TcpIntegrationSpecSupport { _: AkkaSpec ⇒
class TestSetup(shouldBindServer: Boolean = true) {
- val bindHandler = TestProbe()
- val endpoint = temporaryServerAddress()
+ val bindHandler: akka.testkit.TestProbe = TestProbe()
+ val endpoint: java.net.InetSocketAddress = temporaryServerAddress()
if (shouldBindServer) bindServer()
def bindServer(): Unit = {
- val bindCommander = TestProbe()
+ val bindCommander: akka.testkit.TestProbe = TestProbe()
bindCommander.send(IO(Tcp), Bind(bindHandler.ref, endpoint, options = bindOptions))
bindCommander.expectMsg(Bound(endpoint))
}
def establishNewClientConnection(): (TestProbe, ActorRef, TestProbe, ActorRef) = {
- val connectCommander = TestProbe()
+ val connectCommander: akka.testkit.TestProbe = TestProbe()
connectCommander.send(IO(Tcp), Connect(endpoint, options = connectOptions))
val Connected(`endpoint`, localAddress) = connectCommander.expectMsgType[Connected]
- val clientHandler = TestProbe()
+ val clientHandler: akka.testkit.TestProbe = TestProbe()
connectCommander.sender() ! Register(clientHandler.ref)
val Connected(`localAddress`, `endpoint`) = bindHandler.expectMsgType[Connected]
- val serverHandler = TestProbe()
+ val serverHandler: akka.testkit.TestProbe = TestProbe()
bindHandler.sender() ! Register(serverHandler.ref)
(clientHandler, connectCommander.sender(), serverHandler, bindHandler.sender())
@@ -42,7 +42,7 @@ trait TcpIntegrationSpecSupport { _: AkkaSpec ⇒
@tailrec final def expectReceivedData(handler: TestProbe, remaining: Int): Unit =
if (remaining > 0) {
- val recv = handler.expectMsgType[Received]
+ val recv: akka.io.Tcp.Received = handler.expectMsgType[Received]
expectReceivedData(handler, remaining - recv.data.size)
}
diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala
index 897ee8a..e46d307 100644
--- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala
@@ -106,7 +106,7 @@ class TcpListenerSpec extends AkkaSpec("""
"react to Unbind commands by replying with Unbound and stopping itself" in new TestSetup(pullMode = false) {
bindListener()
- val unbindCommander = TestProbe()
+ val unbindCommander: akka.testkit.TestProbe = TestProbe()
unbindCommander.send(listener, Unbind)
unbindCommander.expectMsg(Unbound)
@@ -119,7 +119,7 @@ class TcpListenerSpec extends AkkaSpec("""
attemptConnectionToEndpoint()
listener ! ChannelAcceptable
- val channel = expectWorkerForCommand
+ val channel: java.nio.channels.SocketChannel = expectWorkerForCommand
EventFilter.warning(pattern = "selector capacity limit", occurrences = 1) intercept {
listener ! FailedRegisterIncoming(channel)
@@ -128,18 +128,18 @@ class TcpListenerSpec extends AkkaSpec("""
}
}
- val counter = Iterator.from(0)
+ val counter: Iterator[Int] = Iterator.from(0)
class TestSetup(pullMode: Boolean) {
- val handler = TestProbe()
- val handlerRef = handler.ref
- val bindCommander = TestProbe()
- val parent = TestProbe()
- val selectorRouter = TestProbe()
- val endpoint = SocketUtil.temporaryServerAddress()
+ val handler: akka.testkit.TestProbe = TestProbe()
+ val handlerRef: akka.actor.ActorRef = handler.ref
+ val bindCommander: akka.testkit.TestProbe = TestProbe()
+ val parent: akka.testkit.TestProbe = TestProbe()
+ val selectorRouter: akka.testkit.TestProbe = TestProbe()
+ val endpoint: java.net.InetSocketAddress = SocketUtil.temporaryServerAddress()
- var registerCallReceiver = TestProbe()
- var interestCallReceiver = TestProbe()
+ var registerCallReceiver: akka.testkit.TestProbe = TestProbe()
+ var interestCallReceiver: akka.testkit.TestProbe = TestProbe()
private val parentRef = TestActorRef(new ListenerParent(pullMode))
@@ -156,7 +156,7 @@ class TcpListenerSpec extends AkkaSpec("""
def attemptConnectionToEndpoint(): Unit = new Socket(endpoint.getHostName, endpoint.getPort)
- def listener = parentRef.underlyingActor.listener
+ def listener: akka.actor.ActorRef = parentRef.underlyingActor.listener
def expectWorkerForCommand: SocketChannel =
selectorRouter.expectMsgPF() {
@@ -167,7 +167,7 @@ class TcpListenerSpec extends AkkaSpec("""
}
private class ListenerParent(pullMode: Boolean) extends Actor with ChannelRegistry {
- val listener = context.actorOf(
+ val listener: akka.actor.ActorRef = context.actorOf(
props = Props(classOf[TcpListener], selectorRouter.ref, Tcp(system), this, bindCommander.ref,
Bind(handler.ref, endpoint, 100, Nil, pullMode)).withDeploy(Deploy.local),
name = "test-listener-" + counter.next())
@@ -175,7 +175,7 @@ class TcpListenerSpec extends AkkaSpec("""
def receive: Receive = {
case msg ⇒ parent.ref forward msg
}
- override def supervisorStrategy = SupervisorStrategy.stoppingStrategy
+ override def supervisorStrategy: akka.actor.SupervisorStrategy = SupervisorStrategy.stoppingStrategy
def register(channel: SelectableChannel, initialOps: Int)(implicit channelActor: ActorRef): Unit =
registerCallReceiver.ref.tell(initialOps, channelActor)
diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala
index 660bc56..ca02d7d 100644
--- a/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala
@@ -14,17 +14,17 @@ class UdpConnectedIntegrationSpec extends AkkaSpec("""
akka.actor.serialize-creators = on
""") with ImplicitSender {
- val addresses = temporaryServerAddresses(5, udp = true)
+ val addresses: scala.collection.immutable.IndexedSeq[java.net.InetSocketAddress] = temporaryServerAddresses(5, udp = true)
def bindUdp(address: InetSocketAddress, handler: ActorRef): ActorRef = {
- val commander = TestProbe()
+ val commander: akka.testkit.TestProbe = TestProbe()
commander.send(IO(Udp), Udp.Bind(handler, address))
commander.expectMsg(Udp.Bound(address))
commander.sender()
}
def connectUdp(localAddress: Option[InetSocketAddress], remoteAddress: InetSocketAddress, handler: ActorRef): ActorRef = {
- val commander = TestProbe()
+ val commander: akka.testkit.TestProbe = TestProbe()
commander.send(IO(UdpConnected), UdpConnected.Connect(handler, remoteAddress, localAddress, Nil))
commander.expectMsg(UdpConnected.Connected)
commander.sender()
@@ -33,13 +33,13 @@ class UdpConnectedIntegrationSpec extends AkkaSpec("""
"The UDP connection oriented implementation" must {
"be able to send and receive without binding" in {
- val serverAddress = addresses(0)
- val server = bindUdp(serverAddress, testActor)
- val data1 = ByteString("To infinity and beyond!")
- val data2 = ByteString("All your datagram belong to us")
+ val serverAddress: java.net.InetSocketAddress = addresses(0)
+ val server: akka.actor.ActorRef = bindUdp(serverAddress, testActor)
+ val data1: akka.util.ByteString = ByteString("To infinity and beyond!")
+ val data2: akka.util.ByteString = ByteString("All your datagram belong to us")
connectUdp(localAddress = None, serverAddress, testActor) ! UdpConnected.Send(data1)
- val clientAddress = expectMsgPF() {
+ val clientAddress: java.net.InetSocketAddress = expectMsgPF() {
case Udp.Received(d, a) ⇒
d should ===(data1)
a
@@ -51,11 +51,11 @@ class UdpConnectedIntegrationSpec extends AkkaSpec("""
}
"be able to send and receive with binding" in {
- val serverAddress = addresses(1)
- val clientAddress = addresses(2)
- val server = bindUdp(serverAddress, testActor)
- val data1 = ByteString("To infinity and beyond!")
- val data2 = ByteString("All your datagram belong to us")
+ val serverAddress: java.net.InetSocketAddress = addresses(1)
+ val clientAddress: java.net.InetSocketAddress = addresses(2)
+ val server: akka.actor.ActorRef = bindUdp(serverAddress, testActor)
+ val data1: akka.util.ByteString = ByteString("To infinity and beyond!")
+ val data2: akka.util.ByteString = ByteString("All your datagram belong to us")
connectUdp(Some(clientAddress), serverAddress, testActor) ! UdpConnected.Send(data1)
expectMsgPF() {
@@ -70,12 +70,12 @@ class UdpConnectedIntegrationSpec extends AkkaSpec("""
}
"be able to unbind and bind again successfully" in {
- val serverAddress = addresses(3)
- val clientAddress = addresses(4)
- val server1 = bindUdp(serverAddress, testActor)
+ val serverAddress: java.net.InetSocketAddress = addresses(3)
+ val clientAddress: java.net.InetSocketAddress = addresses(4)
+ val server1: akka.actor.ActorRef = bindUdp(serverAddress, testActor)
- val data1 = ByteString("test")
- val client = connectUdp(Some(clientAddress), serverAddress, testActor)
+ val data1: akka.util.ByteString = ByteString("test")
+ val client: akka.actor.ActorRef = connectUdp(Some(clientAddress), serverAddress, testActor)
client ! UdpConnected.Send(data1)
expectMsgType[Udp.Received].data should ===(data1)
@@ -84,7 +84,7 @@ class UdpConnectedIntegrationSpec extends AkkaSpec("""
expectMsg(Udp.Unbound)
// Reusing the address
- val server2 = bindUdp(serverAddress, testActor)
+ val server2: akka.actor.ActorRef = bindUdp(serverAddress, testActor)
client ! UdpConnected.Send(data1)
expectMsgType[Udp.Received].data should ===(data1)
diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala
index a363968..c5e8dd3 100644
--- a/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala
@@ -20,20 +20,20 @@ class UdpIntegrationSpec extends AkkaSpec("""
akka.actor.serialize-creators = on""") with ImplicitSender {
def bindUdp(handler: ActorRef): InetSocketAddress = {
- val commander = TestProbe()
+ val commander: akka.testkit.TestProbe = TestProbe()
commander.send(IO(Udp), Bind(handler, new InetSocketAddress("127.0.0.1", 0)))
commander.expectMsgType[Bound].localAddress
}
def bindUdp(address: InetSocketAddress, handler: ActorRef): ActorRef = {
- val commander = TestProbe()
+ val commander: akka.testkit.TestProbe = TestProbe()
commander.send(IO(Udp), Bind(handler, address))
commander.expectMsg(Bound(address))
commander.sender()
}
def createSimpleSender(): ActorRef = {
- val commander = TestProbe()
+ val commander: akka.testkit.TestProbe = TestProbe()
commander.send(IO(Udp), SimpleSender)
commander.expectMsg(SimpleSenderReady)
commander.sender()
@@ -42,32 +42,32 @@ class UdpIntegrationSpec extends AkkaSpec("""
"The UDP Fire-and-Forget implementation" must {
"be able to send without binding" in {
- val serverAddress = bindUdp(testActor)
- val data = ByteString("To infinity and beyond!")
- val simpleSender = createSimpleSender()
+ val serverAddress: java.net.InetSocketAddress = bindUdp(testActor)
+ val data: akka.util.ByteString = ByteString("To infinity and beyond!")
+ val simpleSender: akka.actor.ActorRef = createSimpleSender()
simpleSender ! Send(data, serverAddress)
expectMsgType[Received].data should ===(data)
}
"be able to deliver subsequent messages after address resolution failure" in {
- val unresolvableServerAddress = new InetSocketAddress("some-unresolvable-host", 10000)
- val cmd = Send(ByteString("Can't be delivered"), unresolvableServerAddress)
- val simpleSender = createSimpleSender()
+ val unresolvableServerAddress: java.net.InetSocketAddress = new InetSocketAddress("some-unresolvable-host", 10000)
+ val cmd: akka.io.Udp.Send = Send(ByteString("Can't be delivered"), unresolvableServerAddress)
+ val simpleSender: akka.actor.ActorRef = createSimpleSender()
simpleSender ! cmd
expectMsgType[CommandFailed].cmd should ===(cmd)
- val serverAddress = bindUdp(testActor)
- val data = ByteString("To infinity and beyond!")
+ val serverAddress: java.net.InetSocketAddress = bindUdp(testActor)
+ val data: akka.util.ByteString = ByteString("To infinity and beyond!")
simpleSender ! Send(data, serverAddress)
expectMsgType[Received].data should ===(data)
}
"be able to send several packet back and forth with binding" in {
val Seq(serverAddress, clientAddress) = temporaryServerAddresses(2, udp = true)
- val server = bindUdp(serverAddress, testActor)
- val client = bindUdp(clientAddress, testActor)
- val data = ByteString("Fly little packet!")
+ val server: akka.actor.ActorRef = bindUdp(serverAddress, testActor)
+ val client: akka.actor.ActorRef = bindUdp(clientAddress, testActor)
+ val data: akka.util.ByteString = ByteString("Fly little packet!")
def checkSendingToClient(): Unit = {
server ! Send(data, clientAddress)
@@ -95,24 +95,24 @@ class UdpIntegrationSpec extends AkkaSpec("""
}
"call SocketOption.beforeBind method before bind." in {
- val commander = TestProbe()
- val assertOption = AssertBeforeBind()
+ val commander: akka.testkit.TestProbe = TestProbe()
+ val assertOption: akka.io.AssertBeforeBind = AssertBeforeBind()
commander.send(IO(Udp), Bind(testActor, new InetSocketAddress("127.0.0.1", 0), options = List(assertOption)))
commander.expectMsgType[Bound]
assert(assertOption.beforeCalled === 1)
}
"call SocketOption.afterConnect method after binding." in {
- val commander = TestProbe()
- val assertOption = AssertAfterChannelBind()
+ val commander: akka.testkit.TestProbe = TestProbe()
+ val assertOption: akka.io.AssertAfterChannelBind = AssertAfterChannelBind()
commander.send(IO(Udp), Bind(testActor, new InetSocketAddress("127.0.0.1", 0), options = List(assertOption)))
commander.expectMsgType[Bound]
assert(assertOption.afterCalled === 1)
}
"call DatagramChannelCreator.create method when opening channel" in {
- val commander = TestProbe()
- val assertOption = AssertOpenDatagramChannel()
+ val commander: akka.testkit.TestProbe = TestProbe()
+ val assertOption: akka.io.AssertOpenDatagramChannel = AssertOpenDatagramChannel()
commander.send(IO(Udp), Bind(testActor, new InetSocketAddress("127.0.0.1", 0), options = List(assertOption)))
commander.expectMsgType[Bound]
assert(assertOption.openCalled === 1)
@@ -135,7 +135,7 @@ private case class AssertAfterChannelBind() extends SocketOptionV2 {
@volatile
var afterCalled = 0
- override def afterBind(s: DatagramSocket) = {
+ override def afterBind(s: DatagramSocket): Unit = {
assert(s.isBound)
afterCalled += 1
}
@@ -145,7 +145,7 @@ private case class AssertOpenDatagramChannel() extends DatagramChannelCreator {
@volatile
var openCalled = 0
- override def create() = {
+ override def create(): java.nio.channels.DatagramChannel = {
openCalled += 1
super.create()
}
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala
index ca8b90b..276f5ff 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala
@@ -18,16 +18,16 @@ class AskSpec extends AkkaSpec {
"The “ask” pattern" must {
"send request to actor and wrap the answer in Future" in {
- implicit val timeout = Timeout(5.seconds)
- val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } }))
- val f = echo ? "ping"
+ implicit val timeout: akka.util.Timeout = Timeout(5.seconds)
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ sender() ! x } }))
+ val f: scala.concurrent.Future[Any] = echo ? "ping"
f.futureValue should ===("ping")
}
"return broken promises on DeadLetters" in {
- implicit val timeout = Timeout(5 seconds)
- val dead = system.actorFor("/system/deadLetters")
- val f = dead.ask(42)(1 second)
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
+ val dead: akka.actor.ActorRef = system.actorFor("/system/deadLetters")
+ val f: scala.concurrent.Future[Any] = dead.ask(42)(1 second)
f.isCompleted should ===(true)
f.value.get match {
case Failure(_: AskTimeoutException) ⇒
@@ -36,9 +36,9 @@ class AskSpec extends AkkaSpec {
}
"return broken promises on EmptyLocalActorRefs" in {
- implicit val timeout = Timeout(5 seconds)
- val empty = system.actorFor("unknown")
- val f = empty ? 3.14
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
+ val empty: akka.actor.ActorRef = system.actorFor("unknown")
+ val f: scala.concurrent.Future[Any] = empty ? 3.14
f.isCompleted should ===(true)
f.value.get match {
case Failure(_: AskTimeoutException) ⇒
@@ -47,8 +47,8 @@ class AskSpec extends AkkaSpec {
}
"return broken promises on unsupported ActorRefs" in {
- implicit val timeout = Timeout(5 seconds)
- val f = ask(null: ActorRef, 3.14)
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
+ val f: scala.concurrent.Future[Any] = ask(null: ActorRef, 3.14)
f.isCompleted should ===(true)
intercept[IllegalArgumentException] {
Await.result(f, timeout.duration)
@@ -56,76 +56,76 @@ class AskSpec extends AkkaSpec {
}
"return broken promises on 0 timeout" in {
- implicit val timeout = Timeout(0 seconds)
- val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } }))
- val f = echo ? "foo"
- val expectedMsg = "Timeout length must be positive, question not sent to [%s]. Sender[null] sent the message of type \"java.lang.String\"." format echo
+ implicit val timeout: akka.util.Timeout = Timeout(0 seconds)
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ sender() ! x } }))
+ val f: scala.concurrent.Future[Any] = echo ? "foo"
+ val expectedMsg: String = "Timeout length must be positive, question not sent to [%s]. Sender[null] sent the message of type \"java.lang.String\"." format echo
intercept[IllegalArgumentException] {
Await.result(f, timeout.duration)
}.getMessage should ===(expectedMsg)
}
"return broken promises on < 0 timeout" in {
- implicit val timeout = Timeout(-1000 seconds)
- val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } }))
- val f = echo ? "foo"
- val expectedMsg = "Timeout length must be positive, question not sent to [%s]. Sender[null] sent the message of type \"java.lang.String\"." format echo
+ implicit val timeout: akka.util.Timeout = Timeout(-1000 seconds)
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ sender() ! x } }))
+ val f: scala.concurrent.Future[Any] = echo ? "foo"
+ val expectedMsg: String = "Timeout length must be positive, question not sent to [%s]. Sender[null] sent the message of type \"java.lang.String\"." format echo
intercept[IllegalArgumentException] {
Await.result(f, timeout.duration)
}.getMessage should ===(expectedMsg)
}
"include target information in AskTimeout" in {
- implicit val timeout = Timeout(0.5 seconds)
- val silentOne = system.actorOf(Props.empty, "silent")
- val f = silentOne ? "noreply"
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val silentOne: akka.actor.ActorRef = system.actorOf(Props.empty, "silent")
+ val f: scala.concurrent.Future[Any] = silentOne ? "noreply"
intercept[AskTimeoutException] {
Await.result(f, 1 second)
}.getMessage.contains("/user/silent") should ===(true)
}
"include timeout information in AskTimeout" in {
- implicit val timeout = Timeout(0.5 seconds)
- val f = system.actorOf(Props.empty) ? "noreply"
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val f: scala.concurrent.Future[Any] = system.actorOf(Props.empty) ? "noreply"
intercept[AskTimeoutException] {
Await.result(f, 1 second)
}.getMessage should include(timeout.duration.toMillis.toString)
}
"include sender information in AskTimeout" in {
- implicit val timeout = Timeout(0.5 seconds)
- implicit val sender = system.actorOf(Props.empty)
- val f = system.actorOf(Props.empty) ? "noreply"
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ implicit val sender: akka.actor.ActorRef = system.actorOf(Props.empty)
+ val f: scala.concurrent.Future[Any] = system.actorOf(Props.empty) ? "noreply"
intercept[AskTimeoutException] {
Await.result(f, 1 second)
}.getMessage.contains(sender.toString) should ===(true)
}
"include message class information in AskTimeout" in {
- implicit val timeout = Timeout(0.5 seconds)
- val f = system.actorOf(Props.empty) ? "noreply"
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val f: scala.concurrent.Future[Any] = system.actorOf(Props.empty) ? "noreply"
intercept[AskTimeoutException] {
Await.result(f, 1 second)
}.getMessage.contains("\"java.lang.String\"") should ===(true)
}
"work for ActorSelection" in {
- implicit val timeout = Timeout(5 seconds)
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
import system.dispatcher
- val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } }), "select-echo")
- val identityFuture = (system.actorSelection("/user/select-echo") ? Identify(None))
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ sender() ! x } }), "select-echo")
+ val identityFuture: scala.concurrent.Future[akka.actor.ActorRef] = (system.actorSelection("/user/select-echo") ? Identify(None))
.mapTo[ActorIdentity].map(_.ref.get)
Await.result(identityFuture, 5 seconds) should ===(echo)
}
"work when reply uses actor selection" in {
- implicit val timeout = Timeout(5 seconds)
- val deadListener = TestProbe()
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ context.actorSelection(sender().path) ! x } }), "select-echo2")
- val f = echo ? "hi"
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ context.actorSelection(sender().path) ! x } }), "select-echo2")
+ val f: scala.concurrent.Future[Any] = echo ? "hi"
Await.result(f, 1 seconds) should ===("hi")
@@ -133,12 +133,12 @@ class AskSpec extends AkkaSpec {
}
"throw AskTimeoutException on using *" in {
- implicit val timeout = Timeout(0.5 seconds)
- val deadListener = TestProbe()
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ context.actorSelection("/temp/*") ! x } }), "select-echo3")
- val f = echo ? "hi"
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor { def receive: PartialFunction[Any, Unit] = { case x ⇒ context.actorSelection("/temp/*") ! x } }), "select-echo3")
+ val f: scala.concurrent.Future[Any] = echo ? "hi"
intercept[AskTimeoutException] {
Await.result(f, 1 seconds)
}
@@ -147,19 +147,19 @@ class AskSpec extends AkkaSpec {
}
"throw AskTimeoutException on using .." in {
- implicit val timeout = Timeout(0.5 seconds)
- val deadListener = TestProbe()
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val echo = system.actorOf(Props(new Actor {
- def receive = {
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case x ⇒
- val name = sender.path.name
- val parent = sender.path.parent
+ val name: String = sender.path.name
+ val parent: akka.actor.ActorPath = sender.path.parent
context.actorSelection(parent / ".." / "temp" / name) ! x
}
}), "select-echo4")
- val f = echo ? "hi"
+ val f: scala.concurrent.Future[Any] = echo ? "hi"
intercept[AskTimeoutException] {
Await.result(f, 1 seconds) should ===("hi")
}
@@ -168,19 +168,19 @@ class AskSpec extends AkkaSpec {
}
"send to DeadLetter when child does not exist" in {
- implicit val timeout = Timeout(0.5 seconds)
- val deadListener = TestProbe()
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val echo = system.actorOf(Props(new Actor {
- def receive = {
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case x ⇒
- val name = sender.path.name
- val parent = sender.path.parent
+ val name: String = sender.path.name
+ val parent: akka.actor.ActorPath = sender.path.parent
context.actorSelection(parent / "missing") ! x
}
}), "select-echo5")
- val f = echo ? "hi"
+ val f: scala.concurrent.Future[Any] = echo ? "hi"
intercept[AskTimeoutException] {
Await.result(f, 1 seconds) should ===("hi")
}
@@ -188,19 +188,19 @@ class AskSpec extends AkkaSpec {
}
"send DeadLetter when answering to grandchild" in {
- implicit val timeout = Timeout(0.5 seconds)
- val deadListener = TestProbe()
+ implicit val timeout: akka.util.Timeout = Timeout(0.5 seconds)
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val echo = system.actorOf(Props(new Actor {
- def receive = {
+ val echo: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case x ⇒
- val name = sender.path.name
- val parent = sender.path.parent
+ val name: String = sender.path.name
+ val parent: akka.actor.ActorPath = sender.path.parent
context.actorSelection(sender().path / "missing") ! x
}
}), "select-echo6")
- val f = echo ? "hi"
+ val f: scala.concurrent.Future[Any] = echo ? "hi"
intercept[AskTimeoutException] {
Await.result(f, 1 seconds) should ===(ActorSelectionMessage("hi", Vector(SelectChildName("missing")), false))
}
@@ -208,22 +208,22 @@ class AskSpec extends AkkaSpec {
}
"allow watching the promiseActor and send Terminated() when completes" in {
- implicit val timeout = Timeout(300 millis)
- val p = TestProbe()
+ implicit val timeout: akka.util.Timeout = Timeout(300 millis)
+ val p: akka.testkit.TestProbe = TestProbe()
- val act = system.actorOf(Props(new Actor {
- def receive = {
+ val act: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ p.ref ! sender() → msg
}
}))
- val f = (act ? "ask").mapTo[String]
+ val f: scala.concurrent.Future[String] = (act ? "ask").mapTo[String]
val (promiseActorRef, "ask") = p.expectMsgType[(ActorRef, String)]
watch(promiseActorRef)
promiseActorRef ! "complete"
- val completed = f.futureValue
+ val completed: String = f.futureValue
completed should ===("complete")
expectTerminated(promiseActorRef, 1.second)
}
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala
index 565731e..0a85431 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala
@@ -27,7 +27,7 @@ class TestActor(probe: ActorRef) extends Actor {
probe ! "STARTED"
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "DIE" ⇒ context.stop(self)
case "THROW" ⇒ throw new TestActor.NormalException
case "THROW_STOPPING_EXCEPTION" ⇒ throw new TestActor.StoppingException
@@ -42,17 +42,17 @@ object TestParentActor {
}
class TestParentActor(probe: ActorRef, supervisorProps: Props) extends Actor {
- val supervisor = context.actorOf(supervisorProps)
+ val supervisor: akka.actor.ActorRef = context.actorOf(supervisorProps)
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case other ⇒ probe.forward(other)
}
}
class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
- def supervisorProps(probeRef: ActorRef) = {
- val options = Backoff.onFailure(TestActor.props(probeRef), "someChildName", 200 millis, 10 seconds, 0.0)
+ def supervisorProps(probeRef: ActorRef): akka.actor.Props = {
+ val options: akka.pattern.BackoffOptions = Backoff.onFailure(TestActor.props(probeRef), "someChildName", 200 millis, 10 seconds, 0.0)
.withSupervisorStrategy(OneForOneStrategy(maxNrOfRetries = 4, withinTimeRange = 30 seconds) {
case _: TestActor.StoppingException ⇒ SupervisorStrategy.Stop
})
@@ -60,16 +60,16 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
}
trait Setup {
- val probe = TestProbe()
- val supervisor = system.actorOf(supervisorProps(probe.ref))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val supervisor: akka.actor.ActorRef = system.actorOf(supervisorProps(probe.ref))
probe.expectMsg("STARTED")
}
trait Setup2 {
- val probe = TestProbe()
- val parent = system.actorOf(TestParentActor.props(probe.ref, supervisorProps(probe.ref)))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val parent: akka.actor.ActorRef = system.actorOf(TestParentActor.props(probe.ref, supervisorProps(probe.ref)))
probe.expectMsg("STARTED")
- val child = probe.lastSender
+ val child: akka.actor.ActorRef = probe.lastSender
}
"BackoffOnRestartSupervisor" must {
@@ -101,7 +101,7 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
// Verify that we only have one child at this point by selecting all the children
// under the supervisor and broadcasting to them.
// If there exists more than one child, we will get more than one reply.
- val supervisorChildSelection = system.actorSelection(supervisor.path / "*")
+ val supervisorChildSelection: akka.actor.ActorSelection = system.actorSelection(supervisor.path / "*")
supervisorChildSelection.tell("testmsg", probe.ref)
probe.expectMsg("testmsg")
probe.expectNoMsg
@@ -124,7 +124,7 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
}
class SlowlyFailingActor(latch: CountDownLatch) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "THROW" ⇒
sender ! "THROWN"
throw new NormalException
@@ -138,12 +138,12 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
}
"accept commands while child is terminating" in {
- val postStopLatch = new CountDownLatch(1)
- val options = Backoff.onFailure(Props(new SlowlyFailingActor(postStopLatch)), "someChildName", 1 nanos, 1 nanos, 0.0)
+ val postStopLatch: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
+ val options: akka.pattern.BackoffOptions = Backoff.onFailure(Props(new SlowlyFailingActor(postStopLatch)), "someChildName", 1 nanos, 1 nanos, 0.0)
.withSupervisorStrategy(OneForOneStrategy(loggingEnabled = false) {
case _: TestActor.StoppingException ⇒ SupervisorStrategy.Stop
})
- val supervisor = system.actorOf(BackoffSupervisor.props(options))
+ val supervisor: akka.actor.ActorRef = system.actorOf(BackoffSupervisor.props(options))
supervisor ! BackoffSupervisor.GetCurrentChild
// new instance
@@ -193,15 +193,15 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
}
"respect withinTimeRange property of OneForOneStrategy" in {
- val probe = TestProbe()
+ val probe: akka.testkit.TestProbe = TestProbe()
// withinTimeRange indicates the time range in which maxNrOfRetries will cause the child to
// stop. IE: If we restart more than maxNrOfRetries in a time range longer than withinTimeRange
// that is acceptable.
- val options = Backoff.onFailure(TestActor.props(probe.ref), "someChildName", 300 millis, 10 seconds, 0.0)
+ val options: akka.pattern.BackoffOptions = Backoff.onFailure(TestActor.props(probe.ref), "someChildName", 300 millis, 10 seconds, 0.0)
.withSupervisorStrategy(OneForOneStrategy(withinTimeRange = 1 seconds, maxNrOfRetries = 3) {
case _: TestActor.StoppingException ⇒ SupervisorStrategy.Stop
})
- val supervisor = system.actorOf(BackoffSupervisor.props(options))
+ val supervisor: akka.actor.ActorRef = system.actorOf(BackoffSupervisor.props(options))
probe.expectMsg("STARTED")
filterException[TestActor.TestException] {
probe.watch(supervisor)
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala
index 3585f05..b9724c4 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala
@@ -20,7 +20,7 @@ object BackoffSupervisorSpec {
}
class Child(probe: ActorRef) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "boom" ⇒ throw new TestException
case msg ⇒ probe ! msg
}
@@ -32,7 +32,7 @@ object BackoffSupervisorSpec {
}
class ManualChild(probe: ActorRef) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "boom" ⇒ throw new TestException
case msg ⇒
probe ! msg
@@ -44,15 +44,15 @@ object BackoffSupervisorSpec {
class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
import BackoffSupervisorSpec._
- def onStopOptions(props: Props = Child.props(testActor)) = Backoff.onStop(props, "c1", 100.millis, 3.seconds, 0.2)
- def onFailureOptions(props: Props = Child.props(testActor)) = Backoff.onFailure(props, "c1", 100.millis, 3.seconds, 0.2)
- def create(options: BackoffOptions) = system.actorOf(BackoffSupervisor.props(options))
+ def onStopOptions(props: Props = Child.props(testActor)): akka.pattern.BackoffOptions = Backoff.onStop(props, "c1", 100.millis, 3.seconds, 0.2)
+ def onFailureOptions(props: Props = Child.props(testActor)): akka.pattern.BackoffOptions = Backoff.onFailure(props, "c1", 100.millis, 3.seconds, 0.2)
+ def create(options: BackoffOptions): akka.actor.ActorRef = system.actorOf(BackoffSupervisor.props(options))
"BackoffSupervisor" must {
"start child again when it stops when using `Backoff.onStop`" in {
- val supervisor = create(onStopOptions())
+ val supervisor: akka.actor.ActorRef = create(onStopOptions())
supervisor ! BackoffSupervisor.GetCurrentChild
- val c1 = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
+ val c1: akka.actor.ActorRef = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
watch(c1)
c1 ! PoisonPill
expectTerminated(c1)
@@ -64,7 +64,7 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
}
"forward messages to the child" in {
- def assertForward(supervisor: ActorRef) = {
+ def assertForward(supervisor: ActorRef): String = {
supervisor ! "hello"
expectMsg("hello")
}
@@ -73,9 +73,9 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
}
"support custom supervision strategy" in {
- def assertCustomStrategy(supervisor: ActorRef) = {
+ def assertCustomStrategy(supervisor: ActorRef): Unit = {
supervisor ! BackoffSupervisor.GetCurrentChild
- val c1 = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
+ val c1: akka.actor.ActorRef = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
watch(c1)
c1 ! "boom"
expectTerminated(c1)
@@ -86,10 +86,10 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
}
}
filterException[TestException] {
- val stoppingStrategy = OneForOneStrategy() {
+ val stoppingStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case _: TestException ⇒ SupervisorStrategy.Stop
}
- val restartingStrategy = OneForOneStrategy() {
+ val restartingStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case _: TestException ⇒ SupervisorStrategy.Restart
}
@@ -105,9 +105,9 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
"support default stopping strategy when using `Backoff.onStop`" in {
filterException[TestException] {
- val supervisor = create(onStopOptions().withDefaultStoppingStrategy)
+ val supervisor: akka.actor.ActorRef = create(onStopOptions().withDefaultStoppingStrategy)
supervisor ! BackoffSupervisor.GetCurrentChild
- val c1 = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
+ val c1: akka.actor.ActorRef = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
watch(c1)
supervisor ! BackoffSupervisor.GetRestartCount
expectMsg(BackoffSupervisor.RestartCount(0))
@@ -127,9 +127,9 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
"support manual reset" in {
filterException[TestException] {
- def assertManualReset(supervisor: ActorRef) = {
+ def assertManualReset(supervisor: ActorRef): akka.pattern.BackoffSupervisor.RestartCount = {
supervisor ! BackoffSupervisor.GetCurrentChild
- val c1 = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
+ val c1: akka.actor.ActorRef = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
watch(c1)
c1 ! "boom"
expectTerminated(c1)
@@ -156,10 +156,10 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
expectMsg(BackoffSupervisor.RestartCount(0))
}
- val stoppingStrategy = OneForOneStrategy() {
+ val stoppingStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case _: TestException ⇒ SupervisorStrategy.Stop
}
- val restartingStrategy = OneForOneStrategy() {
+ val restartingStrategy: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case _: TestException ⇒ SupervisorStrategy.Restart
}
@@ -177,9 +177,9 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
"reply to sender if replyWhileStopped is specified" in {
filterException[TestException] {
- val supervisor = create(Backoff.onFailure(Child.props(testActor), "c1", 100.seconds, 300.seconds, 0.2).withReplyWhileStopped("child was stopped"))
+ val supervisor: akka.actor.ActorRef = create(Backoff.onFailure(Child.props(testActor), "c1", 100.seconds, 300.seconds, 0.2).withReplyWhileStopped("child was stopped"))
supervisor ! BackoffSupervisor.GetCurrentChild
- val c1 = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
+ val c1: akka.actor.ActorRef = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
watch(c1)
supervisor ! BackoffSupervisor.GetRestartCount
expectMsg(BackoffSupervisor.RestartCount(0))
@@ -199,9 +199,9 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender {
"not reply to sender if replyWhileStopped is NOT specified" in {
filterException[TestException] {
- val supervisor = create(Backoff.onFailure(Child.props(testActor), "c1", 100.seconds, 300.seconds, 0.2))
+ val supervisor: akka.actor.ActorRef = create(Backoff.onFailure(Child.props(testActor), "c1", 100.seconds, 300.seconds, 0.2))
supervisor ! BackoffSupervisor.GetCurrentChild
- val c1 = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
+ val c1: akka.actor.ActorRef = expectMsgType[BackoffSupervisor.CurrentChild].ref.get
watch(c1)
supervisor ! BackoffSupervisor.GetRestartCount
expectMsg(BackoffSupervisor.RestartCount(0))
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala
index 50d7a7c..8b145e5 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala
@@ -9,12 +9,12 @@ import scala.concurrent.duration._
import scala.concurrent.{ Future, Await }
class CircuitBreakerMTSpec extends AkkaSpec {
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
"A circuit breaker being called by many threads" must {
- val callTimeout = 2.second.dilated
- val resetTimeout = 3.seconds.dilated
+ val callTimeout: scala.concurrent.duration.FiniteDuration = 2.second.dilated
+ val resetTimeout: scala.concurrent.duration.FiniteDuration = 3.seconds.dilated
val maxFailures = 5
- val breaker = new CircuitBreaker(system.scheduler, maxFailures, callTimeout, resetTimeout)
+ val breaker: akka.pattern.CircuitBreaker = new CircuitBreaker(system.scheduler, maxFailures, callTimeout, resetTimeout)
val numberOfTestCalls = 100
def openBreaker(): Unit = {
@@ -32,7 +32,7 @@ class CircuitBreakerMTSpec extends AkkaSpec {
}
def testCallsWithBreaker(): immutable.IndexedSeq[Future[String]] = {
- val aFewActive = new TestLatch(5)
+ val aFewActive: akka.testkit.TestLatch = new TestLatch(5)
for (_ ← 1 to numberOfTestCalls) yield breaker.withCircuitBreaker(Future {
aFewActive.countDown()
Await.ready(aFewActive, 5.seconds.dilated)
@@ -45,22 +45,22 @@ class CircuitBreakerMTSpec extends AkkaSpec {
}
"allow many calls while in closed state with no errors" in {
- val futures = testCallsWithBreaker()
- val result = Await.result(Future.sequence(futures), 5.second.dilated)
+ val futures: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[String]] = testCallsWithBreaker()
+ val result: scala.collection.immutable.IndexedSeq[String] = Await.result(Future.sequence(futures), 5.second.dilated)
result.size should ===(numberOfTestCalls)
result.toSet should ===(Set("succeed"))
}
"transition to open state upon reaching failure limit and fail-fast" in {
openBreaker()
- val futures = testCallsWithBreaker()
- val result = Await.result(Future.sequence(futures), 5.second.dilated)
+ val futures: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[String]] = testCallsWithBreaker()
+ val result: scala.collection.immutable.IndexedSeq[String] = Await.result(Future.sequence(futures), 5.second.dilated)
result.size should ===(numberOfTestCalls)
result.toSet should ===(Set("CBO"))
}
"allow a single call through in half-open state" in {
- val halfOpenLatch = new TestLatch(1)
+ val halfOpenLatch: akka.testkit.TestLatch = new TestLatch(1)
breaker.onHalfOpen(halfOpenLatch.countDown())
openBreaker()
@@ -68,14 +68,14 @@ class CircuitBreakerMTSpec extends AkkaSpec {
// breaker should become half-open after a while
Await.ready(halfOpenLatch, resetTimeout + 1.seconds.dilated)
- val futures = testCallsWithBreaker()
- val result = Await.result(Future.sequence(futures), 5.second.dilated)
+ val futures: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[String]] = testCallsWithBreaker()
+ val result: scala.collection.immutable.IndexedSeq[String] = Await.result(Future.sequence(futures), 5.second.dilated)
result.size should ===(numberOfTestCalls)
result.toSet should ===(Set("succeed", "CBO"))
}
"recover and reset the breaker after the reset timeout" in {
- val halfOpenLatch = new TestLatch(1)
+ val halfOpenLatch: akka.testkit.TestLatch = new TestLatch(1)
breaker.onHalfOpen(halfOpenLatch.countDown())
openBreaker()
@@ -83,13 +83,13 @@ class CircuitBreakerMTSpec extends AkkaSpec {
Await.ready(halfOpenLatch, resetTimeout + 1.seconds.dilated)
// one successful call should close the latch
- val closedLatch = new TestLatch(1)
+ val closedLatch: akka.testkit.TestLatch = new TestLatch(1)
breaker.onClose(closedLatch.countDown())
breaker.withCircuitBreaker(Future("succeed"))
Await.ready(closedLatch, 5.seconds.dilated)
- val futures = testCallsWithBreaker()
- val result = Await.result(Future.sequence(futures), 5.second.dilated)
+ val futures: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[String]] = testCallsWithBreaker()
+ val result: scala.collection.immutable.IndexedSeq[String] = Await.result(Future.sequence(futures), 5.second.dilated)
result.size should ===(numberOfTestCalls)
result.toSet should ===(Set("succeed"))
}
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala
index a299cf5..3709000 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala
@@ -20,17 +20,17 @@ object CircuitBreakerSpec {
class TestException extends RuntimeException
class Breaker(val instance: CircuitBreaker)(implicit system: ActorSystem) extends MockitoSugar {
- val halfOpenLatch = new TestLatch(1)
- val openLatch = new TestLatch(1)
- val closedLatch = new TestLatch(1)
- val callSuccessLatch = new TestLatch(1)
- val callFailureLatch = new TestLatch(1)
- val callTimeoutLatch = new TestLatch(1)
- val callBreakerOpenLatch = new TestLatch(1)
-
- val callSuccessConsumerMock = mock[Long ⇒ Unit]
- val callFailureConsumerMock = mock[Long ⇒ Unit]
- val callTimeoutConsumerMock = mock[Long ⇒ Unit]
+ val halfOpenLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val openLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val closedLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val callSuccessLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val callFailureLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val callTimeoutLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val callBreakerOpenLatch: akka.testkit.TestLatch = new TestLatch(1)
+
+ val callSuccessConsumerMock: Long ⇒ Unit = mock[Long ⇒ Unit]
+ val callFailureConsumerMock: Long ⇒ Unit = mock[Long ⇒ Unit]
+ val callTimeoutConsumerMock: Long ⇒ Unit = mock[Long ⇒ Unit]
def apply(): CircuitBreaker = instance
instance
@@ -52,18 +52,18 @@ object CircuitBreakerSpec {
.onCallBreakerOpen(callBreakerOpenLatch.countDown())
}
- val shortCallTimeout = 50.millis
+ val shortCallTimeout: scala.concurrent.duration.FiniteDuration = 50.millis
def shortCallTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker =
new Breaker(new CircuitBreaker(system.scheduler, 1, shortCallTimeout, 500.millis.dilated))
- val shortResetTimeout = 50.millis
+ val shortResetTimeout: scala.concurrent.duration.FiniteDuration = 50.millis
def shortResetTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker =
new Breaker(new CircuitBreaker(system.scheduler, 1, 1000.millis.dilated, shortResetTimeout))
def longCallTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker =
new Breaker(new CircuitBreaker(system.scheduler, 1, 5 seconds, 500.millis.dilated))
- val longResetTimeout = 5.seconds
+ val longResetTimeout: scala.concurrent.duration.FiniteDuration = 5.seconds
def longResetTimeoutCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker =
new Breaker(new CircuitBreaker(system.scheduler, 1, 100.millis.dilated, longResetTimeout))
@@ -81,40 +81,40 @@ object CircuitBreakerSpec {
class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar {
import CircuitBreakerSpec.TestException
- implicit def ec = system.dispatcher
- implicit def s = system
+ implicit def ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
+ implicit def s: akka.actor.ActorSystem = system
- val awaitTimeout = 2.seconds.dilated
+ val awaitTimeout: scala.concurrent.duration.FiniteDuration = 2.seconds.dilated
def checkLatch(latch: TestLatch): Unit = Await.ready(latch, awaitTimeout)
- def throwException = throw new TestException
+ def throwException: Nothing = throw new TestException
def sayHi = "hi"
- def timeCaptor = ArgumentCaptor.forClass(classOf[Long])
+ def timeCaptor: org.mockito.ArgumentCaptor[Long] = ArgumentCaptor.forClass(classOf[Long])
"A synchronous circuit breaker that is open" must {
"throw exceptions when called before reset timeout" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.openLatch)
- val e = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
+ val e: akka.pattern.CircuitBreakerOpenException = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
(e.remainingDuration > Duration.Zero) should ===(true)
(e.remainingDuration <= CircuitBreakerSpec.longResetTimeout) should ===(true)
}
"transition to half-open on reset timeout" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
}
"still be in open state after calling success method" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.openLatch)
breaker().succeed()
@@ -122,7 +122,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"still be in open state after calling fail method" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.openLatch)
breaker().fail()
@@ -130,13 +130,13 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onHalfOpen during transition to half-open state" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
}
"invoke onCallBreakerOpen when called before reset timeout" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.openLatch)
intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
@@ -144,8 +144,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallFailure when call results in exception" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.callFailureLatch)
@@ -158,7 +158,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"A synchronous circuit breaker that is half-open" must {
"pass through next call and close on success" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
assert("hi" == breaker().withSyncCircuitBreaker(sayHi))
@@ -167,7 +167,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"pass through next call and close on exception" when {
"exception is defined as call succeeded" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
@@ -179,7 +179,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"open on exception in call" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
breaker.openLatch.reset
@@ -189,7 +189,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"open on even number" when {
"even number is defined as failure" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
breaker.openLatch.reset
@@ -199,7 +199,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"open on calling fail method" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
breaker.openLatch.reset
@@ -208,7 +208,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"close on calling success method" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
breaker().succeed()
@@ -216,8 +216,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallSuccess on success" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
@@ -231,8 +231,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallFailure on failure" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
@@ -249,8 +249,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallTimeout on timeout" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
@@ -264,7 +264,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallBreakerOpen while executing other" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
@@ -276,7 +276,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallSuccess after transition to open state" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
@@ -288,12 +288,12 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"A synchronous circuit breaker that is closed" must {
"allow calls through" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
breaker().withSyncCircuitBreaker(sayHi) should ===("hi")
}
"increment failure count on failure" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
breaker().currentFailureCount should ===(0)
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.openLatch)
@@ -302,9 +302,9 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"increment failure count on even number" when {
"even number is considered failure" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
breaker().currentFailureCount should ===(0)
- val result = breaker().withSyncCircuitBreaker(2, CircuitBreakerSpec.evenNumberIsFailure)
+ val result: Int = breaker().withSyncCircuitBreaker(2, CircuitBreakerSpec.evenNumberIsFailure)
checkLatch(breaker.openLatch)
breaker().currentFailureCount should ===(1)
@@ -313,7 +313,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"increment failure count on fail method" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
breaker().currentFailureCount should ===(0)
breaker().fail()
checkLatch(breaker.openLatch)
@@ -321,10 +321,10 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"reset failure count after success" in {
- val breaker = CircuitBreakerSpec.multiFailureCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb()
breaker().currentFailureCount should ===(0)
intercept[TestException] {
- val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
+ val ct: Thread = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
}
breaker().currentFailureCount should ===(1)
@@ -334,15 +334,15 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"reset failure count after exception in call" when {
"exception is defined as Success" in {
- val breaker = CircuitBreakerSpec.multiFailureCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb()
breaker().currentFailureCount should ===(0)
intercept[TestException] {
- val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
+ val ct: Thread = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
}
breaker().currentFailureCount should ===(1)
- val harmlessException = new TestException
+ val harmlessException: akka.pattern.CircuitBreakerSpec.TestException = new TestException
val harmlessExceptionAsSuccess: Try[String] ⇒ Boolean = {
case Success(_) ⇒ false
case Failure(ex) ⇒ ex != harmlessException
@@ -357,10 +357,10 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"reset failure count after success method" in {
- val breaker = CircuitBreakerSpec.multiFailureCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb()
breaker().currentFailureCount should ===(0)
intercept[TestException] {
- val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
+ val ct: Thread = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
}
breaker().currentFailureCount should ===(1)
@@ -369,7 +369,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"throw TimeoutException on callTimeout" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
intercept[TimeoutException] {
breaker().withSyncCircuitBreaker {
Thread.sleep(200.millis.dilated.toMillis)
@@ -379,7 +379,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"increment failure count on callTimeout before call finishes" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
Future {
breaker().withSyncCircuitBreaker {
Thread.sleep(1.second.dilated.toMillis)
@@ -391,8 +391,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallSuccess if call succeeds" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withSyncCircuitBreaker(sayHi)
checkLatch(breaker.callSuccessLatch)
@@ -403,8 +403,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallTimeout if call timeouts" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
intercept[TimeoutException](breaker().withSyncCircuitBreaker(Thread.sleep(250.millis.dilated.toMillis)))
checkLatch(breaker.callTimeoutLatch)
@@ -415,8 +415,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallFailure if call fails" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
intercept[TestException](breaker().withSyncCircuitBreaker(throwException))
checkLatch(breaker.callFailureLatch)
@@ -427,7 +427,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onOpen if call fails and breaker transits to open state" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
intercept[TestException](breaker().withSyncCircuitBreaker(throwException))
checkLatch(breaker.openLatch)
@@ -436,7 +436,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"An asynchronous circuit breaker that is open" must {
"throw exceptions when called before reset timeout" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.openLatch)
@@ -445,18 +445,18 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"transition to half-open on reset timeout" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
}
"increase the reset timeout after it transits to open again" in {
- val breaker = CircuitBreakerSpec.nonOneFactorCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.nonOneFactorCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.openLatch)
- val e1 = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
- val shortRemainingDuration = e1.remainingDuration
+ val e1: akka.pattern.CircuitBreakerOpenException = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
+ val shortRemainingDuration: scala.concurrent.duration.FiniteDuration = e1.remainingDuration
Thread.sleep(1000.millis.dilated.toMillis)
checkLatch(breaker.halfOpenLatch)
@@ -466,22 +466,22 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.openLatch)
- val e2 = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
- val longRemainingDuration = e2.remainingDuration
+ val e2: akka.pattern.CircuitBreakerOpenException = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) }
+ val longRemainingDuration: scala.concurrent.duration.FiniteDuration = e2.remainingDuration
(shortRemainingDuration < longRemainingDuration) should ===(true)
}
"invoke onHalfOpen during transition to half-open state" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout) }
checkLatch(breaker.halfOpenLatch)
}
"invoke onCallBreakerOpen when called before reset timeout" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.openLatch)
@@ -491,8 +491,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallFailure when call results in exception" in {
- val breaker = CircuitBreakerSpec.longResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.callFailureLatch)
@@ -505,7 +505,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"An asynchronous circuit breaker that is half-open" must {
"pass through next call and close on success" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
Await.result(breaker().withCircuitBreaker(Future(sayHi)), awaitTimeout) should ===("hi")
@@ -514,7 +514,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"pass through next call and close on exception" when {
"exception is defined as call succeeded" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
val allReturnIsSuccess: Try[String] ⇒ Boolean = _ ⇒ false
@@ -524,7 +524,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"re-open on exception in call" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
breaker.openLatch.reset
@@ -534,7 +534,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"re-open on even number" when {
"even number is defined as failure" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) }
checkLatch(breaker.halfOpenLatch)
breaker.openLatch.reset
@@ -544,7 +544,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"re-open on async failure" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
@@ -554,8 +554,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallSuccess on success" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
@@ -569,8 +569,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallFailure on failure" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(throwException))
@@ -587,8 +587,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallTimeout on timeout" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
@@ -602,8 +602,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onCallBreakerOpen while executing other" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
@@ -614,7 +614,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"pass through next call and invoke onOpen after transition to open state" in {
- val breaker = CircuitBreakerSpec.shortResetTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortResetTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.halfOpenLatch)
@@ -626,12 +626,12 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"An asynchronous circuit breaker that is closed" must {
"allow calls through" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
Await.result(breaker().withCircuitBreaker(Future(sayHi)), awaitTimeout) should ===("hi")
}
"increment failure count on exception" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
intercept[TestException] { Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout) }
checkLatch(breaker.openLatch)
breaker().currentFailureCount should ===(1)
@@ -639,9 +639,9 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"increment failure count on even number" when {
"even number is considered failure" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
breaker().currentFailureCount should ===(0)
- val result = Await.result(breaker().withCircuitBreaker(Future(2), CircuitBreakerSpec.evenNumberIsFailure), awaitTimeout)
+ val result: Int = Await.result(breaker().withCircuitBreaker(Future(2), CircuitBreakerSpec.evenNumberIsFailure), awaitTimeout)
checkLatch(breaker.openLatch)
breaker().currentFailureCount should ===(1)
result should ===(2)
@@ -649,14 +649,14 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"increment failure count on async failure" in {
- val breaker = CircuitBreakerSpec.longCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.longCallTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.openLatch)
breaker().currentFailureCount should ===(1)
}
"reset failure count after success" in {
- val breaker = CircuitBreakerSpec.multiFailureCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb()
breaker().withCircuitBreaker(Future(sayHi))
for (n ← 1 to 4) breaker().withCircuitBreaker(Future(throwException))
awaitCond(breaker().currentFailureCount == 4, awaitTimeout)
@@ -666,12 +666,12 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
"reset failure count after exception in call" when {
"exception is defined as Success" in {
- val breaker = CircuitBreakerSpec.multiFailureCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb()
breaker().withCircuitBreaker(Future(sayHi))
for (n ← 1 to 4) breaker().withCircuitBreaker(Future(throwException))
awaitCond(breaker().currentFailureCount == 4, awaitTimeout)
- val harmlessException = new TestException
+ val harmlessException: akka.pattern.CircuitBreakerSpec.TestException = new TestException
val harmlessExceptionAsSuccess: Try[String] ⇒ Boolean = {
case Success(_) ⇒ false
case Failure(ex) ⇒ ex != harmlessException
@@ -683,9 +683,9 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"increment failure count on callTimeout" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val fut = breaker().withCircuitBreaker(Future {
+ val fut: scala.concurrent.Future[Nothing] = breaker().withCircuitBreaker(Future {
Thread.sleep(150.millis.dilated.toMillis)
throwException
})
@@ -700,8 +700,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallSuccess if call succeeds" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(sayHi))
checkLatch(breaker.callSuccessLatch)
@@ -712,8 +712,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallTimeout if call timeouts" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(Thread.sleep(250.millis.dilated.toMillis)))
checkLatch(breaker.callTimeoutLatch)
@@ -724,8 +724,8 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onCallFailure if call fails" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
- val captor = timeCaptor
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val captor: org.mockito.ArgumentCaptor[Long] = timeCaptor
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.callFailureLatch)
@@ -736,7 +736,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
}
"invoke onOpen if call fails and breaker transits to open state" in {
- val breaker = CircuitBreakerSpec.shortCallTimeoutCb()
+ val breaker: akka.pattern.CircuitBreakerSpec.Breaker = CircuitBreakerSpec.shortCallTimeoutCb()
breaker().withCircuitBreaker(Future(throwException))
checkLatch(breaker.openLatch)
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala
index dcf1ec5..5d8e9e9 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala
@@ -28,7 +28,7 @@ object CircuitBreakerStressSpec {
private var circCount = 0
private def job = {
- val promise = Promise[JobDone.type]()
+ val promise: scala.concurrent.Promise[akka.pattern.CircuitBreakerStressSpec.JobDone.type] = Promise[JobDone.type]()
context.system.scheduler.scheduleOnce(ThreadLocalRandom.current.nextInt(300).millisecond) {
promise.success(JobDone)
@@ -37,7 +37,7 @@ object CircuitBreakerStressSpec {
promise.future
}
- override def receive = {
+ override def receive: PartialFunction[Any, Unit] = {
case JobDone ⇒
doneCount += 1
breaker.withCircuitBreaker(job).pipeTo(self)
@@ -63,8 +63,8 @@ class CircuitBreakerStressSpec extends AkkaSpec with ImplicitSender {
muteDeadLetters(classOf[AnyRef])(system)
"A CircuitBreaker" in {
- val breaker = CircuitBreaker(system.scheduler, 5, 200.millisecond, 200.seconds)
- val stressActors = Vector.fill(3) {
+ val breaker: akka.pattern.CircuitBreaker = CircuitBreaker(system.scheduler, 5, 200.millisecond, 200.seconds)
+ val stressActors: scala.collection.immutable.Vector[akka.actor.ActorRef] = Vector.fill(3) {
system.actorOf(Props(classOf[StressActor], breaker))
}
for (_ ← 0 to 1000; a ← stressActors) {
@@ -74,7 +74,7 @@ class CircuitBreakerStressSpec extends AkkaSpec with ImplicitSender {
Thread.sleep(3000)
stressActors.foreach { a ⇒
a ! GetResult
- val result = expectMsgType[Result]
+ val result: akka.pattern.CircuitBreakerStressSpec.Result = expectMsgType[Result]
result.failCount should be(0)
}
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala
index fd8fe7a..8984201 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala
@@ -14,7 +14,7 @@ import scala.concurrent.duration._
object PatternSpec {
final case class Work(duration: Duration)
class TargetActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case (testLatch: TestLatch, duration: FiniteDuration) ⇒
Await.ready(testLatch, duration)
}
@@ -22,26 +22,26 @@ object PatternSpec {
}
class PatternSpec extends AkkaSpec("akka.actor.serialize-messages = off") {
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
import PatternSpec._
"pattern.gracefulStop" must {
"provide Future for stopping an actor" in {
- val target = system.actorOf(Props[TargetActor])
- val result = gracefulStop(target, 5 seconds)
+ val target: akka.actor.ActorRef = system.actorOf(Props[TargetActor])
+ val result: scala.concurrent.Future[Boolean] = gracefulStop(target, 5 seconds)
Await.result(result, 6 seconds) should ===(true)
}
"complete Future when actor already terminated" in {
- val target = system.actorOf(Props[TargetActor])
+ val target: akka.actor.ActorRef = system.actorOf(Props[TargetActor])
Await.ready(gracefulStop(target, 5 seconds), 6 seconds)
Await.ready(gracefulStop(target, 1 millis), 1 second)
}
"complete Future with AskTimeoutException when actor not terminated within timeout" in {
- val target = system.actorOf(Props[TargetActor])
- val latch = TestLatch()
+ val target: akka.actor.ActorRef = system.actorOf(Props[TargetActor])
+ val latch: akka.testkit.TestLatch = TestLatch()
target ! ((latch, remainingOrDefault))
intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500 millis), remainingOrDefault) }
latch.open()
@@ -51,17 +51,17 @@ class PatternSpec extends AkkaSpec("akka.actor.serialize-messages = off") {
"pattern.after" must {
"be completed successfully eventually" in {
// TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759
- val f = akka.pattern.after(1 second, using = system.scheduler)(Promise.successful(5).future)
+ val f: scala.concurrent.Future[Int] = akka.pattern.after(1 second, using = system.scheduler)(Promise.successful(5).future)
- val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
+ val r: scala.concurrent.Future[Int] = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
Await.result(r, remainingOrDefault) should ===(5)
}
"be completed abnormally eventually" in {
// TODO after is unfortunately shadowed by ScalaTest, fix as part of #3759
- val f = akka.pattern.after(1 second, using = system.scheduler)(Promise.failed(new IllegalStateException("Mexico")).future)
+ val f: scala.concurrent.Future[Nothing] = akka.pattern.after(1 second, using = system.scheduler)(Promise.failed(new IllegalStateException("Mexico")).future)
- val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
+ val r: scala.concurrent.Future[Int] = Future.firstCompletedOf(Seq(Promise[Int]().future, f))
intercept[IllegalStateException] { Await.result(r, remainingOrDefault) }.getMessage should ===("Mexico")
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/PipeToSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/PipeToSpec.scala
index 4078fd7..61b1b70 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/PipeToSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/PipeToSpec.scala
@@ -16,33 +16,33 @@ class PipeToSpec extends AkkaSpec {
"PipeTo" must {
"work" in {
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
Future(42) pipeTo p.ref
p.expectMsg(42)
}
"signal failure" in {
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
Future.failed(new Exception("failed")) pipeTo p.ref
p.expectMsgType[Status.Failure].cause.getMessage should ===("failed")
}
"pick up an implicit sender()" in {
- val p = TestProbe()
- implicit val s = testActor
+ val p: akka.testkit.TestProbe = TestProbe()
+ implicit val s: akka.actor.ActorRef = testActor
Future(42) pipeTo p.ref
p.expectMsg(42)
p.lastSender should ===(s)
}
"work in Java form" in {
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
pipe(Future(42)) to p.ref
p.expectMsg(42)
}
"work in Java form with sender()" in {
- val p = TestProbe()
+ val p: akka.testkit.TestProbe = TestProbe()
pipe(Future(42)) to (p.ref, testActor)
p.expectMsg(42)
p.lastSender should ===(testActor)
@@ -53,38 +53,38 @@ class PipeToSpec extends AkkaSpec {
"PipeToSelection" must {
"work" in {
- val p = TestProbe()
- val sel = system.actorSelection(p.ref.path)
+ val p: akka.testkit.TestProbe = TestProbe()
+ val sel: akka.actor.ActorSelection = system.actorSelection(p.ref.path)
Future(42) pipeToSelection sel
p.expectMsg(42)
}
"signal failure" in {
- val p = TestProbe()
- val sel = system.actorSelection(p.ref.path)
+ val p: akka.testkit.TestProbe = TestProbe()
+ val sel: akka.actor.ActorSelection = system.actorSelection(p.ref.path)
Future.failed(new Exception("failed")) pipeToSelection sel
p.expectMsgType[Status.Failure].cause.getMessage should ===("failed")
}
"pick up an implicit sender()" in {
- val p = TestProbe()
- val sel = system.actorSelection(p.ref.path)
- implicit val s = testActor
+ val p: akka.testkit.TestProbe = TestProbe()
+ val sel: akka.actor.ActorSelection = system.actorSelection(p.ref.path)
+ implicit val s: akka.actor.ActorRef = testActor
Future(42) pipeToSelection sel
p.expectMsg(42)
p.lastSender should ===(s)
}
"work in Java form" in {
- val p = TestProbe()
- val sel = system.actorSelection(p.ref.path)
+ val p: akka.testkit.TestProbe = TestProbe()
+ val sel: akka.actor.ActorSelection = system.actorSelection(p.ref.path)
pipe(Future(42)) to sel
p.expectMsg(42)
}
"work in Java form with sender()" in {
- val p = TestProbe()
- val sel = system.actorSelection(p.ref.path)
+ val p: akka.testkit.TestProbe = TestProbe()
+ val sel: akka.actor.ActorSelection = system.actorSelection(p.ref.path)
pipe(Future(42)) to (sel, testActor)
p.expectMsg(42)
p.lastSender should ===(testActor)
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala
index 0a8bb0a..8396ba5 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala
@@ -24,10 +24,10 @@ class PromiseRefSpec extends AkkaSpec with ImplicitSender {
"The PromiseRef" must {
"complete promise with received message" in {
- val promiseRef = PromiseRef(5.seconds)
+ val promiseRef: akka.pattern.PromiseRef[Any] = PromiseRef(5.seconds)
- val target = system.actorOf(Props(new Actor {
- def receive = { case Request(replyTo) ⇒ replyTo ! Response }
+ val target: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case Request(replyTo) ⇒ replyTo ! Response }
}))
target ! Request(promiseRef.ref)
@@ -41,10 +41,10 @@ class PromiseRefSpec extends AkkaSpec with ImplicitSender {
}
"receive only one message" in {
- val deadListener = TestProbe()
+ val deadListener: akka.testkit.TestProbe = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
- val promiseRef = PromiseRef(5.seconds)
+ val promiseRef: akka.pattern.PromiseRef[Any] = PromiseRef(5.seconds)
promiseRef.ref ! FirstMessage
promiseRef.future.futureValue should ===(FirstMessage)
@@ -54,16 +54,16 @@ class PromiseRefSpec extends AkkaSpec with ImplicitSender {
}
"work with explicitly constructed PromiseRef's" in {
- val promise = Promise[Int]()
+ val promise: scala.concurrent.Promise[Int] = Promise[Int]()
- val alice = system.actorOf(Props(new Actor {
- def receive = { case Response ⇒ promise.success(42) }
+ val alice: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case Response ⇒ promise.success(42) }
}))
- val promiseRef = PromiseRef.wrap(alice, promise)
+ val promiseRef: akka.pattern.PromiseRef[Int] = PromiseRef.wrap(alice, promise)
- val bob = system.actorOf(Props(new Actor {
- def receive = { case Request(replyTo) ⇒ replyTo ! Response }
+ val bob: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = { case Request(replyTo) ⇒ replyTo ! Response }
}))
bob ! Request(promiseRef.ref)
diff --git a/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala
index df85284..e97b55c 100644
--- a/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala
@@ -19,29 +19,29 @@ class ExplicitAskSpec extends AkkaSpec {
"The “ask” pattern with explicit sender" must {
"allow to access an explicit reference to actor to respond to" in {
- implicit val timeout = Timeout(5.seconds)
+ implicit val timeout: akka.util.Timeout = Timeout(5.seconds)
- val target = system.actorOf(Props(new Actor {
- def receive = {
+ val target: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Request(respondTo) ⇒ respondTo ! Response(self)
}
}))
- val f = target ? (respondTo ⇒ Request(respondTo))
+ val f: scala.concurrent.Future[Any] = target ? (respondTo ⇒ Request(respondTo))
f.futureValue should ===(Response(target))
}
"work for ActorSelection" in {
- implicit val timeout = Timeout(5.seconds)
+ implicit val timeout: akka.util.Timeout = Timeout(5.seconds)
- val target = system.actorOf(Props(new Actor {
- def receive = {
+ val target: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case Request(respondTo) ⇒ respondTo ! Response(self)
}
}), "select-echo")
- val selection = system.actorSelection("/user/select-echo")
- val f = selection ? (respondTo ⇒ Request(respondTo))
+ val selection: akka.actor.ActorSelection = system.actorSelection("/user/select-echo")
+ val f: scala.concurrent.Future[Any] = selection ? (respondTo ⇒ Request(respondTo))
f.futureValue should ===(Response(target))
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala
index 69a6189..bbbe88f 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala
@@ -13,14 +13,14 @@ import org.scalatest.BeforeAndAfterEach
import java.net.URLEncoder
object BalancingSpec {
- val counter = new AtomicInteger(1)
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger(1)
class Worker(latch: TestLatch) extends Actor {
- lazy val id = counter.getAndIncrement()
+ lazy val id: Int = counter.getAndIncrement()
override def preStart(): Unit = latch.countDown()
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case msg: Int ⇒
if (id != 1)
Await.ready(latch, 1.minute)
@@ -31,10 +31,10 @@ object BalancingSpec {
}
class Parent extends Actor {
- val pool = context.actorOf(BalancingPool(2).props(routeeProps =
+ val pool: akka.actor.ActorRef = context.actorOf(BalancingPool(2).props(routeeProps =
Props(classOf[Worker], TestLatch(0)(context.system))))
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ pool.forward(msg)
}
}
@@ -79,13 +79,13 @@ class BalancingSpec extends AkkaSpec(
}
// all but one worker are blocked
- val replies1 = receiveN(iterationCount - poolSize + 1)
+ val replies1: scala.collection.immutable.Seq[AnyRef] = receiveN(iterationCount - poolSize + 1)
expectNoMsg(1.second)
// all replies from the unblocked worker so far
replies1.toSet should be(Set(1))
latch.open()
- val replies2 = receiveN(poolSize - 1)
+ val replies2: scala.collection.immutable.Seq[AnyRef] = receiveN(poolSize - 1)
// the remaining replies come from the blocked
replies2.toSet should be((2 to poolSize).toSet)
expectNoMsg(500.millis)
@@ -95,22 +95,22 @@ class BalancingSpec extends AkkaSpec(
"balancing pool" must {
"deliver messages in a balancing fashion when defined programatically" in {
- val latch = TestLatch(poolSize)
- val pool = system.actorOf(BalancingPool(poolSize).props(routeeProps =
+ val latch: akka.testkit.TestLatch = TestLatch(poolSize)
+ val pool: akka.actor.ActorRef = system.actorOf(BalancingPool(poolSize).props(routeeProps =
Props(classOf[Worker], latch)), name = "balancingPool-1")
test(pool, latch)
}
"deliver messages in a balancing fashion when defined in config" in {
- val latch = TestLatch(poolSize)
- val pool = system.actorOf(FromConfig().props(routeeProps =
+ val latch: akka.testkit.TestLatch = TestLatch(poolSize)
+ val pool: akka.actor.ActorRef = system.actorOf(FromConfig().props(routeeProps =
Props(classOf[Worker], latch)), name = "balancingPool-2")
test(pool, latch)
}
"deliver messages in a balancing fashion when overridden in config" in {
- val latch = TestLatch(poolSize)
- val pool = system.actorOf(BalancingPool(1).props(routeeProps =
+ val latch: akka.testkit.TestLatch = TestLatch(poolSize)
+ val pool: akka.actor.ActorRef = system.actorOf(BalancingPool(1).props(routeeProps =
Props(classOf[Worker], latch)), name = "balancingPool-3")
test(pool, latch)
}
@@ -122,7 +122,7 @@ class BalancingSpec extends AkkaSpec(
}
"work with encoded actor names" in {
- val encName = URLEncoder.encode("abcå6#$€xyz", "utf-8")
+ val encName: String = URLEncoder.encode("abcå6#$€xyz", "utf-8")
// % is a valid config key character (e.g. %C3%A5)
system.actorOf(Props[Parent], encName) ! 1001
expectMsgType[Int]
diff --git a/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala
index dd39097..14fc9c5 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala
@@ -11,7 +11,7 @@ import akka.pattern.ask
object BroadcastSpec {
class TestActor extends Actor {
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
}
@@ -20,26 +20,26 @@ class BroadcastSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
"broadcast group" must {
"broadcast message using !" in {
- val doneLatch = new TestLatch(2)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(2)
- val counter1 = new AtomicInteger
- val actor1 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter1: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor1: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter1.addAndGet(msg)
}
}))
- val counter2 = new AtomicInteger
- val actor2 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter2: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter2.addAndGet(msg)
}
}))
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(BroadcastGroup(paths).props())
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(BroadcastGroup(paths).props())
routedActor ! 1
routedActor ! "end"
@@ -50,11 +50,11 @@ class BroadcastSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
}
"broadcast message using ?" in {
- val doneLatch = new TestLatch(2)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(2)
- val counter1 = new AtomicInteger
- val actor1 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter1: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor1: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒
counter1.addAndGet(msg)
@@ -62,16 +62,16 @@ class BroadcastSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
}
}))
- val counter2 = new AtomicInteger
- val actor2 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter2: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter2.addAndGet(msg)
}
}))
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(BroadcastGroup(paths).props())
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(BroadcastGroup(paths).props())
routedActor ? 1
routedActor ! "end"
diff --git a/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala
index e0f6da8..8ac502b 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala
@@ -80,18 +80,18 @@ object ConfiguredLocalRoutingSpec {
}
class EchoProps extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "get" ⇒ sender() ! context.props
}
}
class SendRefAtStartup(testActor: ActorRef) extends Actor {
testActor ! self
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
class Parent extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case (p: Props, name: String) ⇒
sender() ! context.actorOf(p, name)
}
@@ -112,7 +112,7 @@ class ConfiguredLocalRoutingSpec extends AkkaSpec(ConfiguredLocalRoutingSpec.con
def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = {
for (i ← 1 to n) yield {
- val msg = i.toString
+ val msg: String = i.toString
router.tell(msg, probe.ref)
probe.expectMsg(msg)
probe.lastSender.path
@@ -122,32 +122,32 @@ class ConfiguredLocalRoutingSpec extends AkkaSpec(ConfiguredLocalRoutingSpec.con
"RouterConfig" must {
"be picked up from Props" in {
- val actor = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]), "someOther")
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]), "someOther")
routerConfig(actor) should ===(RoundRobinPool(12))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds)
}
"be overridable in config" in {
- val actor = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]), "config")
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinPool(12).props(routeeProps = Props[EchoProps]), "config")
routerConfig(actor) should ===(RandomPool(nrOfInstances = 4, usePoolDispatcher = true))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds)
}
"use routees.paths from config" in {
- val actor = system.actorOf(RandomPool(12).props(routeeProps = Props[EchoProps]), "paths")
+ val actor: akka.actor.ActorRef = system.actorOf(RandomPool(12).props(routeeProps = Props[EchoProps]), "paths")
routerConfig(actor) should ===(RandomGroup(List("/user/service1", "/user/service2")))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds)
}
"be overridable in explicit deployment" in {
- val actor = system.actorOf(FromConfig.props(routeeProps = Props[EchoProps]).
+ val actor: akka.actor.ActorRef = system.actorOf(FromConfig.props(routeeProps = Props[EchoProps]).
withDeploy(Deploy(routerConfig = RoundRobinPool(12))), "someOther")
routerConfig(actor) should ===(RoundRobinPool(12))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds)
}
"be overridable in config even with explicit deployment" in {
- val actor = system.actorOf(FromConfig.props(routeeProps = Props[EchoProps]).
+ val actor: akka.actor.ActorRef = system.actorOf(FromConfig.props(routeeProps = Props[EchoProps]).
withDeploy(Deploy(routerConfig = RoundRobinPool(12))), "config")
routerConfig(actor) should ===(RandomPool(nrOfInstances = 4, usePoolDispatcher = true))
Await.result(gracefulStop(actor, 3 seconds), 3 seconds)
@@ -160,15 +160,15 @@ class ConfiguredLocalRoutingSpec extends AkkaSpec(ConfiguredLocalRoutingSpec.con
}
"not get confused when trying to wildcard-configure children" in {
- val router = system.actorOf(FromConfig.props(routeeProps = Props(classOf[SendRefAtStartup], testActor)), "weird")
- val recv = Set() ++ (for (_ ← 1 to 3) yield expectMsgType[ActorRef])
- val expc = Set('a', 'b', 'c') map (i ⇒ system.actorFor("/user/weird/$" + i))
+ val router: akka.actor.ActorRef = system.actorOf(FromConfig.props(routeeProps = Props(classOf[SendRefAtStartup], testActor)), "weird")
+ val recv: scala.collection.immutable.Set[akka.actor.ActorRef] = Set() ++ (for (_ ← 1 to 3) yield expectMsgType[ActorRef])
+ val expc: scala.collection.immutable.Set[akka.actor.ActorRef] = Set('a', 'b', 'c') map (i ⇒ system.actorFor("/user/weird/$" + i))
recv should ===(expc)
expectNoMsg(1 second)
}
"support custom router" in {
- val myrouter = system.actorOf(FromConfig.props(), "myrouter")
+ val myrouter: akka.actor.ActorRef = system.actorOf(FromConfig.props(), "myrouter")
myrouter ! "foo"
expectMsg("bar")
}
@@ -176,12 +176,12 @@ class ConfiguredLocalRoutingSpec extends AkkaSpec(ConfiguredLocalRoutingSpec.con
"load settings from config for local child router of system actor" in {
// we don't really support deployment configuration of system actors, but
// it's used for the pool of the SimpleDnsManager "/IO-DNS/inet-address"
- val probe = TestProbe()
- val parent = system.asInstanceOf[ExtendedActorSystem].systemActorOf(Props[Parent], "sys-parent")
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val parent: akka.actor.ActorRef = system.asInstanceOf[ExtendedActorSystem].systemActorOf(Props[Parent], "sys-parent")
parent.tell((FromConfig.props(echoActorProps), "round"), probe.ref)
- val router = probe.expectMsgType[ActorRef]
- val replies = collectRouteePaths(probe, router, 10)
- val children = replies.toSet
+ val router: akka.actor.ActorRef = probe.expectMsgType[ActorRef]
+ val replies: scala.collection.immutable.Seq[akka.actor.ActorPath] = collectRouteePaths(probe, router, 10)
+ val children: scala.collection.immutable.Set[akka.actor.ActorPath] = replies.toSet
children should have size 6
system.stop(router)
}
diff --git a/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala
index 68c70f6..5fe6185 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala
@@ -31,14 +31,14 @@ object ConsistentHashingRouterSpec {
"""
class Echo extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x: ConsistentHashableEnvelope ⇒ sender() ! s"Unexpected envelope: $x"
case _ ⇒ sender() ! self
}
}
final case class Msg(key: Any, data: String) extends ConsistentHashable {
- override def consistentHashKey = key
+ override def consistentHashKey: Any = key
}
final case class MsgKey(name: String)
@@ -48,29 +48,29 @@ object ConsistentHashingRouterSpec {
class ConsistentHashingRouterSpec extends AkkaSpec(ConsistentHashingRouterSpec.config) with DefaultTimeout with ImplicitSender {
import ConsistentHashingRouterSpec._
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
- val router1 = system.actorOf(FromConfig.props(Props[Echo]), "router1")
+ val router1: akka.actor.ActorRef = system.actorOf(FromConfig.props(Props[Echo]), "router1")
"consistent hashing router" must {
"create routees from configuration" in {
- val currentRoutees = Await.result(router1 ? GetRoutees, timeout.duration).asInstanceOf[Routees]
+ val currentRoutees: akka.routing.Routees = Await.result(router1 ? GetRoutees, timeout.duration).asInstanceOf[Routees]
currentRoutees.routees.size should ===(3)
}
"select destination based on consistentHashKey of the message" in {
router1 ! Msg("a", "A")
- val destinationA = expectMsgType[ActorRef]
+ val destinationA: akka.actor.ActorRef = expectMsgType[ActorRef]
router1 ! ConsistentHashableEnvelope(message = "AA", hashKey = "a")
expectMsg(destinationA)
router1 ! Msg(17, "B")
- val destinationB = expectMsgType[ActorRef]
+ val destinationB: akka.actor.ActorRef = expectMsgType[ActorRef]
router1 ! ConsistentHashableEnvelope(message = "BB", hashKey = 17)
expectMsg(destinationB)
router1 ! Msg(MsgKey("c"), "C")
- val destinationC = expectMsgType[ActorRef]
+ val destinationC: akka.actor.ActorRef = expectMsgType[ActorRef]
router1 ! ConsistentHashableEnvelope(message = "CC", hashKey = MsgKey("c"))
expectMsg(destinationC)
}
@@ -79,21 +79,21 @@ class ConsistentHashingRouterSpec extends AkkaSpec(ConsistentHashingRouterSpec.c
def hashMapping: ConsistentHashMapping = {
case Msg2(key, data) ⇒ key
}
- val router2 = system.actorOf(ConsistentHashingPool(nrOfInstances = 1, hashMapping = hashMapping).
+ val router2: akka.actor.ActorRef = system.actorOf(ConsistentHashingPool(nrOfInstances = 1, hashMapping = hashMapping).
props(Props[Echo]), "router2")
router2 ! Msg2("a", "A")
- val destinationA = expectMsgType[ActorRef]
+ val destinationA: akka.actor.ActorRef = expectMsgType[ActorRef]
router2 ! ConsistentHashableEnvelope(message = "AA", hashKey = "a")
expectMsg(destinationA)
router2 ! Msg2(17, "B")
- val destinationB = expectMsgType[ActorRef]
+ val destinationB: akka.actor.ActorRef = expectMsgType[ActorRef]
router2 ! ConsistentHashableEnvelope(message = "BB", hashKey = 17)
expectMsg(destinationB)
router2 ! Msg2(MsgKey("c"), "C")
- val destinationC = expectMsgType[ActorRef]
+ val destinationC: akka.actor.ActorRef = expectMsgType[ActorRef]
router2 ! ConsistentHashableEnvelope(message = "CC", hashKey = MsgKey("c"))
expectMsg(destinationC)
}
diff --git a/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala
index 1c1e130..c730d93 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala
@@ -28,7 +28,7 @@ object MetricsBasedResizerSpec {
*/
class TestLatchingActor(implicit timeout: Timeout) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Latches(first, second) ⇒
first.countDown()
Try(Await.ready(second, timeout.duration))
@@ -38,7 +38,7 @@ object MetricsBasedResizerSpec {
def routee(implicit system: ActorSystem, timeout: Timeout): ActorRefRoutee =
ActorRefRoutee(system.actorOf(Props(new TestLatchingActor)))
- def routees(num: Int = 10)(implicit system: ActorSystem, timeout: Timeout) = (1 to num).map(_ ⇒ routee).toVector
+ def routees(num: Int = 10)(implicit system: ActorSystem, timeout: Timeout): Vector[akka.routing.ActorRefRoutee] = (1 to num).map(_ ⇒ routee).toVector
case class TestRouter(routees: Vector[ActorRefRoutee])(implicit system: ActorSystem, timeout: Timeout) {
@@ -48,9 +48,9 @@ object MetricsBasedResizerSpec {
await: Boolean,
l: TestLatch = TestLatch(),
routeeIdx: Int = Random.nextInt(routees.length)): Latches = {
- val target = routees(routeeIdx)
- val first = TestLatch()
- val latches = Latches(first, l)
+ val target: akka.routing.ActorRefRoutee = routees(routeeIdx)
+ val first: akka.testkit.TestLatch = TestLatch()
+ val latches: akka.routing.MetricsBasedResizerSpec.Latches = Latches(first, l)
target.send(latches, Actor.noSender)
msgs = msgs + l
if (await) Await.ready(first, timeout.duration)
@@ -60,7 +60,7 @@ object MetricsBasedResizerSpec {
def close(): Unit = msgs.foreach(_.open())
def sendToAll(await: Boolean): Seq[Latches] = {
- val sentMessages = routees.indices.map(i ⇒ mockSend(await, routeeIdx = i))
+ val sentMessages: scala.collection.immutable.IndexedSeq[akka.routing.MetricsBasedResizerSpec.Latches] = routees.indices.map(i ⇒ mockSend(await, routeeIdx = i))
sentMessages
}
@@ -78,20 +78,20 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"MetricsBasedResizer isTimeForResize" must {
"be true with empty history" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.record = ResizeRecord(checkTime = 0)
resizer.isTimeForResize(0) should ===(true)
}
"be false if the last resize is too close within actionInterval enough history" in {
- val resizer = DefaultOptimalSizeExploringResizer(actionInterval = 10.seconds)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(actionInterval = 10.seconds)
resizer.record = ResizeRecord(checkTime = System.nanoTime() - 8.seconds.toNanos)
resizer.isTimeForResize(100) should ===(false)
}
"be true if the last resize is before actionInterval ago" in {
- val resizer = DefaultOptimalSizeExploringResizer(actionInterval = 10.seconds)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(actionInterval = 10.seconds)
resizer.record = ResizeRecord(checkTime = System.nanoTime() - 11.seconds.toNanos)
resizer.isTimeForResize(100) should ===(true)
@@ -102,14 +102,14 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"MetricsBasedResizer reportMessageCount" must {
"record last messageCounter correctly" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.reportMessageCount(Vector(routee), 3)
resizer.record.messageCount shouldBe 3
}
"record last totalQueueLength correctly" in {
- val resizer = DefaultOptimalSizeExploringResizer()
- val router = TestRouter(routees(2))
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
resizer.reportMessageCount(router.routees, router.msgs.size)
resizer.record.totalQueueLength shouldBe 0
@@ -124,7 +124,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"start an underutilizationStreak when not fully utilized" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.reportMessageCount(routees(2), 0)
resizer.record.underutilizationStreak should not be empty
resizer.record.underutilizationStreak.get.start.isBefore(LocalDateTime.now.plusSeconds(1)) shouldBe true
@@ -132,11 +132,11 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"stop an underutilizationStreak when fully utilized" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.record = ResizeRecord(
underutilizationStreak = Some(UnderUtilizationStreak(start = LocalDateTime.now.minusHours(1), highestUtilization = 1)))
- val router = TestRouter(routees(2))
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
router.sendToAll(await = true)
resizer.reportMessageCount(router.routees, router.msgs.size)
@@ -147,7 +147,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"leave the underutilizationStreak start date unchanged when not fully utilized" in {
val start: LocalDateTime = LocalDateTime.now.minusHours(1)
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.record = ResizeRecord(
underutilizationStreak = Some(UnderUtilizationStreak(start = start, highestUtilization = 1)))
@@ -156,11 +156,11 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"leave the underutilizationStreak highestUtilization unchanged if current utilization is lower" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.record = ResizeRecord(
underutilizationStreak = Some(UnderUtilizationStreak(start = LocalDateTime.now, highestUtilization = 2)))
- val router = TestRouter(routees(2))
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
router.mockSend(await = true)
resizer.reportMessageCount(router.routees, router.msgs.size)
@@ -170,11 +170,11 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"update the underutilizationStreak highestUtilization if current utilization is higher" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.record = ResizeRecord(
underutilizationStreak = Some(UnderUtilizationStreak(start = LocalDateTime.now, highestUtilization = 1)))
- val router = TestRouter(routees(3))
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(3))
router.mockSend(await = true, routeeIdx = 0)
router.mockSend(await = true, routeeIdx = 1)
@@ -185,8 +185,8 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"not record a performance log when it's not fully utilized in two consecutive checks" in {
- val resizer = DefaultOptimalSizeExploringResizer()
- val router = TestRouter(routees(2))
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
resizer.reportMessageCount(router.routees, router.msgs.size)
router.sendToAll(await = true)
@@ -198,13 +198,13 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"not record the performance log when no message is processed" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.record = ResizeRecord(
totalQueueLength = 2,
messageCount = 2,
checkTime = System.nanoTime())
- val router = TestRouter(routees(2))
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
router.sendToAll(await = true)
resizer.reportMessageCount(router.routees, router.msgs.size)
@@ -215,9 +215,9 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"record the performance log with the correct pool size" in {
- val resizer = DefaultOptimalSizeExploringResizer()
- val router = TestRouter(routees(2))
- val msgs = router.sendToAll(await = true)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
+ val msgs: Seq[akka.routing.MetricsBasedResizerSpec.Latches] = router.sendToAll(await = true)
resizer.reportMessageCount(router.routees, router.msgs.size)
msgs.head.second.open()
@@ -230,12 +230,12 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"record the performance log with the correct process speed" in {
- val resizer = DefaultOptimalSizeExploringResizer()
- val router = TestRouter(routees(2))
- val msgs1 = router.sendToAll(await = true)
- val msgs2 = router.sendToAll(await = false) //make sure the routees are still busy after the first batch of messages get processed.
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
+ val msgs1: Seq[akka.routing.MetricsBasedResizerSpec.Latches] = router.sendToAll(await = true)
+ val msgs2: Seq[akka.routing.MetricsBasedResizerSpec.Latches] = router.sendToAll(await = false) //make sure the routees are still busy after the first batch of messages get processed.
- val before = System.nanoTime()
+ val before: Long = System.nanoTime()
resizer.reportMessageCount(router.routees, router.msgs.size) //updates the records
msgs1.foreach(_.second.open()) //process two messages
@@ -248,9 +248,9 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
resizer.reportMessageCount(router.routees, router.msgs.size)
- val after = System.nanoTime()
- val millisPassed = (after - before) / 1000000
- val tenPercent = millisPassed / 10
+ val after: Long = System.nanoTime()
+ val millisPassed: Long = (after - before) / 1000000
+ val tenPercent: Long = millisPassed / 10
resizer.performanceLog(2).toMillis shouldBe (millisPassed / 2 +- tenPercent)
router.close()
@@ -258,16 +258,16 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"update the old performance log entry with updated speed " in {
val oldSpeed = 50
- val resizer = DefaultOptimalSizeExploringResizer(
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(
weightOfLatestMetric = 0.5)
resizer.performanceLog = Map(2 → oldSpeed.milliseconds)
- val router = TestRouter(routees(2))
- val msgs1 = router.sendToAll(await = true)
- val msgs2 = router.sendToAll(await = false) //make sure the routees are still busy after the first batch of messages get processed.
+ val router: akka.routing.MetricsBasedResizerSpec.TestRouter = TestRouter(routees(2))
+ val msgs1: Seq[akka.routing.MetricsBasedResizerSpec.Latches] = router.sendToAll(await = true)
+ val msgs2: Seq[akka.routing.MetricsBasedResizerSpec.Latches] = router.sendToAll(await = false) //make sure the routees are still busy after the first batch of messages get processed.
- val before = System.nanoTime()
+ val before: Long = System.nanoTime()
resizer.reportMessageCount(router.routees, router.msgs.size) //updates the records
msgs1.foreach(_.second.open()) //process two messages
@@ -280,10 +280,10 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
resizer.reportMessageCount(router.routees, router.msgs.size)
- val after = System.nanoTime()
- val millisPassed = (after - before) / 1000000
- val tenPercent = millisPassed / 10
- val newSpeed = millisPassed / 2
+ val after: Long = System.nanoTime()
+ val millisPassed: Long = (after - before) / 1000000
+ val tenPercent: Long = millisPassed / 10
+ val newSpeed: Long = millisPassed / 2
resizer.performanceLog(2).toMillis shouldBe ((newSpeed + oldSpeed) / 2 +- tenPercent)
@@ -294,7 +294,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"MetricsBasedResizer resize" must {
"downsize to close to the highest retention when a streak of underutilization started downsizeAfterUnderutilizedFor" in {
- val resizer = DefaultOptimalSizeExploringResizer(
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(
downsizeAfterUnderutilizedFor = 72.hours,
downsizeRatio = 0.5)
@@ -304,27 +304,27 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"does not downsize on empty history" in {
- val resizer = DefaultOptimalSizeExploringResizer()
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer()
resizer.resize(routees()) should be(0)
}
"always go to lowerBound if below it" in {
- val resizer = DefaultOptimalSizeExploringResizer(lowerBound = 50, upperBound = 100)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(lowerBound = 50, upperBound = 100)
resizer.resize(routees(20)) should be(30)
}
"always go to uppperBound if above it" in {
- val resizer = DefaultOptimalSizeExploringResizer(upperBound = 50)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(upperBound = 50)
resizer.resize(routees(80)) should be(-30)
}
"explore when there is performance log but not go beyond exploreStepSize" in {
- val resizer = DefaultOptimalSizeExploringResizer(
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(
exploreStepSize = 0.3,
explorationProbability = 1)
resizer.performanceLog = Map(11 → 1.milli, 13 → 1.millis, 12 → 3.millis)
- val exploreSamples = (1 to 100).map(_ ⇒ resizer.resize(routees(10)))
+ val exploreSamples: scala.collection.immutable.IndexedSeq[Int] = (1 to 100).map(_ ⇒ resizer.resize(routees(10)))
exploreSamples.forall(change ⇒ Math.abs(change) >= 1 && Math.abs(change) <= (10 * 0.3)) should be(true)
}
@@ -332,7 +332,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"MetricsBasedResizer optimize" must {
"optimize towards the fastest pool size" in {
- val resizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0)
resizer.performanceLog = Map(7 → 5.millis, 10 → 3.millis, 11 → 2.millis, 12 → 4.millis)
resizer.resize(routees(10)) should be(1)
resizer.resize(routees(12)) should be(-1)
@@ -340,7 +340,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"ignore further away sample data when optmizing" in {
- val resizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0, numOfAdjacentSizesToConsiderDuringOptimization = 4)
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0, numOfAdjacentSizesToConsiderDuringOptimization = 4)
resizer.performanceLog = Map(
7 → 5.millis,
8 → 2.millis,
@@ -360,9 +360,9 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
"start with lowerbound pool size" in {
- val resizer = DefaultOptimalSizeExploringResizer(lowerBound = 2)
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(Props(new TestLatchingActor)))
- val latches = Latches(TestLatch(), TestLatch(0))
+ val resizer: akka.routing.DefaultOptimalSizeExploringResizer = DefaultOptimalSizeExploringResizer(lowerBound = 2)
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(Props(new TestLatchingActor)))
+ val latches: akka.routing.MetricsBasedResizerSpec.Latches = Latches(TestLatch(), TestLatch(0))
router ! latches
Await.ready(latches.first, timeout.duration)
diff --git a/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala
index 85a8ba3..23a3936 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala
@@ -16,10 +16,10 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
"random pool" must {
"be able to shut down its instance" in {
- val stopLatch = new TestLatch(7)
+ val stopLatch: akka.testkit.TestLatch = new TestLatch(7)
- val actor = system.actorOf(RandomPool(7).props(Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(RandomPool(7).props(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "hello" ⇒ sender() ! "world"
}
@@ -45,18 +45,18 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
"deliver messages in a random fashion" in {
val connectionCount = 10
val iterationCount = 100
- val doneLatch = new TestLatch(connectionCount)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(connectionCount)
- val counter = new AtomicInteger
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
var replies = Map.empty[Int, Int]
for (i ← 0 until connectionCount) {
replies = replies + (i → 0)
}
- val actor = system.actorOf(RandomPool(connectionCount).props(routeeProps =
+ val actor: akka.actor.ActorRef = system.actorOf(RandomPool(connectionCount).props(routeeProps =
Props(new Actor {
- lazy val id = counter.getAndIncrement()
- def receive = {
+ lazy val id: Int = counter.getAndIncrement()
+ def receive: PartialFunction[Any, Unit] = {
case "hit" ⇒ sender() ! id
case "end" ⇒ doneLatch.countDown()
}
@@ -64,7 +64,7 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
for (i ← 0 until iterationCount) {
for (k ← 0 until connectionCount) {
- val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration)
+ val id: Int = Await.result((actor ? "hit").mapTo[Int], timeout.duration)
replies = replies + (id → (replies(id) + 1))
}
}
@@ -79,11 +79,11 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
}
"deliver a broadcast message using the !" in {
- val helloLatch = new TestLatch(6)
- val stopLatch = new TestLatch(6)
+ val helloLatch: akka.testkit.TestLatch = new TestLatch(6)
+ val stopLatch: akka.testkit.TestLatch = new TestLatch(6)
- val actor = system.actorOf(RandomPool(6).props(routeeProps = Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(RandomPool(6).props(routeeProps = Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "hello" ⇒ helloLatch.countDown()
}
diff --git a/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala
index 37acc1e..c69de9f 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala
@@ -29,7 +29,7 @@ object ResizerSpec {
"""
class TestActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case latch: TestLatch ⇒ latch.countDown()
}
}
@@ -50,12 +50,12 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
"Resizer fromConfig" must {
def parseCfg(cfgString: String): Config = {
- val referenceCfg = ConfigFactory.defaultReference(ActorSystem.findClassLoader())
+ val referenceCfg: com.typesafe.config.Config = ConfigFactory.defaultReference(ActorSystem.findClassLoader())
ConfigFactory.parseString(cfgString).withFallback(referenceCfg.getConfig("akka.actor.deployment.default"))
}
"load DefaultResizer from config when resizer is enabled" in {
- val cfg = parseCfg("""
+ val cfg: com.typesafe.config.Config = parseCfg("""
resizer {
enabled = on
}
@@ -64,7 +64,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"load MetricsBasedResizer from config when optimal-size-exploring-resizer is enabled" in {
- val cfg = parseCfg("""
+ val cfg: com.typesafe.config.Config = parseCfg("""
optimal-size-exploring-resizer {
enabled = on
}
@@ -73,7 +73,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"throws exception when both resizer and optimal-size-exploring-resizer is enabled" in {
- val cfg = parseCfg("""
+ val cfg: com.typesafe.config.Config = parseCfg("""
optimal-size-exploring-resizer {
enabled = on
}
@@ -94,22 +94,22 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
"DefaultResizer" must {
"use settings to evaluate capacity" in {
- val resizer = DefaultResizer(
+ val resizer: akka.routing.DefaultResizer = DefaultResizer(
lowerBound = 2,
upperBound = 3)
- val c1 = resizer.capacity(Vector.empty[Routee])
+ val c1: Int = resizer.capacity(Vector.empty[Routee])
c1 should ===(2)
- val current = Vector(
+ val current: scala.collection.immutable.Vector[akka.routing.ActorRefRoutee] = Vector(
ActorRefRoutee(system.actorOf(Props[TestActor])),
ActorRefRoutee(system.actorOf(Props[TestActor])))
- val c2 = resizer.capacity(current)
+ val c2: Int = resizer.capacity(current)
c2 should ===(0)
}
"use settings to evaluate rampUp" in {
- val resizer = DefaultResizer(
+ val resizer: akka.routing.DefaultResizer = DefaultResizer(
lowerBound = 2,
upperBound = 10,
rampupRate = 0.2)
@@ -120,7 +120,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"use settings to evaluate backoff" in {
- val resizer = DefaultResizer(
+ val resizer: akka.routing.DefaultResizer = DefaultResizer(
lowerBound = 2,
upperBound = 10,
backoffThreshold = 0.3,
@@ -136,12 +136,12 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"be possible to define programmatically" in {
- val latch = new TestLatch(3)
+ val latch: akka.testkit.TestLatch = new TestLatch(3)
- val resizer = DefaultResizer(
+ val resizer: akka.routing.DefaultResizer = DefaultResizer(
lowerBound = 2,
upperBound = 3)
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).
props(Props[TestActor]))
router ! latch
@@ -155,9 +155,9 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"be possible to define in configuration" in {
- val latch = new TestLatch(3)
+ val latch: akka.testkit.TestLatch = new TestLatch(3)
- val router = system.actorOf(FromConfig.props(Props[TestActor]), "router1")
+ val router: akka.actor.ActorRef = system.actorOf(FromConfig.props(Props[TestActor]), "router1")
router ! latch
router ! latch
@@ -172,7 +172,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
// make sure the pool starts at the expected lower limit and grows to the upper as needed
// as influenced by the backlog of blocking pooled actors
- val resizer = DefaultResizer(
+ val resizer: akka.routing.DefaultResizer = DefaultResizer(
lowerBound = 3,
upperBound = 5,
rampupRate = 0.1,
@@ -181,9 +181,9 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
messagesPerResize = 1,
backoffThreshold = 0.0)
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case d: FiniteDuration ⇒
Thread.sleep(d.dilated.toMillis); sender() ! "done"
case "echo" ⇒ sender() ! "reply"
@@ -196,7 +196,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
routeeSize(router) should ===(resizer.lowerBound)
- def loop(loops: Int, d: FiniteDuration) = {
+ def loop(loops: Int, d: FiniteDuration): Unit = {
for (m ← 0 until loops) {
router ! d
// sending in too quickly will result in skipped resize due to many resizeInProgress conflicts
@@ -217,7 +217,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"backoff" in within(10 seconds) {
- val resizer = DefaultResizer(
+ val resizer: akka.routing.DefaultResizer = DefaultResizer(
lowerBound = 2,
upperBound = 5,
rampupRate = 1.0,
@@ -226,9 +226,9 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
pressureThreshold = 1,
messagesPerResize = 2)
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case n: Int if n <= 0 ⇒ // done
case n: Int ⇒ Thread.sleep((n millis).dilated.toMillis)
}
@@ -240,7 +240,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
Thread.sleep((20 millis).dilated.toMillis)
}
- val z = routeeSize(router)
+ val z: Int = routeeSize(router)
z should be > (2)
Thread.sleep((300 millis).dilated.toMillis)
diff --git a/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala
index e49eb9c..e796dc2 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala
@@ -22,11 +22,11 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
"round robin pool" must {
"be able to shut down its instance" in {
- val helloLatch = new TestLatch(5)
- val stopLatch = new TestLatch(5)
+ val helloLatch: akka.testkit.TestLatch = new TestLatch(5)
+ val stopLatch: akka.testkit.TestLatch = new TestLatch(5)
- val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "hello" ⇒ helloLatch.countDown()
}
@@ -49,21 +49,21 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
"deliver messages in a round robin fashion" in {
val connectionCount = 10
val iterationCount = 10
- val doneLatch = new TestLatch(connectionCount)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(connectionCount)
- val counter = new AtomicInteger
+ val counter: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
var replies = Map.empty[Int, Int].withDefaultValue(0)
- val actor = system.actorOf(RoundRobinPool(connectionCount).props(routeeProps = Props(new Actor {
- lazy val id = counter.getAndIncrement()
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinPool(connectionCount).props(routeeProps = Props(new Actor {
+ lazy val id: Int = counter.getAndIncrement()
+ def receive: PartialFunction[Any, Unit] = {
case "hit" ⇒ sender() ! id
case "end" ⇒ doneLatch.countDown()
}
})), "round-robin")
for (_ ← 1 to iterationCount; _ ← 1 to connectionCount) {
- val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration)
+ val id: Int = Await.result((actor ? "hit").mapTo[Int], timeout.duration)
replies = replies + (id → (replies(id) + 1))
}
@@ -76,11 +76,11 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
}
"deliver a broadcast message using the !" in {
- val helloLatch = new TestLatch(5)
- val stopLatch = new TestLatch(5)
+ val helloLatch: akka.testkit.TestLatch = new TestLatch(5)
+ val stopLatch: akka.testkit.TestLatch = new TestLatch(5)
- val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
- def receive = {
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "hello" ⇒ helloLatch.countDown()
}
@@ -97,8 +97,8 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
}
"be controlled with management messages" in {
- val actor = system.actorOf(RoundRobinPool(3).props(routeeProps = Props(new Actor {
- def receive = Actor.emptyBehavior
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinPool(3).props(routeeProps = Props(new Actor {
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
})), "round-robin-managed")
routeeSize(actor) should ===(3)
@@ -107,7 +107,7 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
actor ! AdjustPoolSize(-2)
routeeSize(actor) should ===(5)
- val other = ActorSelectionRoutee(system.actorSelection("/user/other"))
+ val other: akka.routing.ActorSelectionRoutee = ActorSelectionRoutee(system.actorSelection("/user/other"))
actor ! AddRoutee(other)
routeeSize(actor) should ===(6)
actor ! RemoveRoutee(other)
@@ -120,13 +120,13 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
"deliver messages in a round robin fashion" in {
val connectionCount = 10
val iterationCount = 10
- val doneLatch = new TestLatch(connectionCount)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(connectionCount)
var replies = Map.empty[String, Int].withDefaultValue(0)
- val paths = (1 to connectionCount) map { n ⇒
- val ref = system.actorOf(Props(new Actor {
- def receive = {
+ val paths: scala.collection.immutable.IndexedSeq[String] = (1 to connectionCount) map { n ⇒
+ val ref: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "hit" ⇒ sender() ! self.path.name
case "end" ⇒ doneLatch.countDown()
}
@@ -134,10 +134,10 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
ref.path.toStringWithoutAddress
}
- val actor = system.actorOf(RoundRobinGroup(paths).props(), "round-robin-group1")
+ val actor: akka.actor.ActorRef = system.actorOf(RoundRobinGroup(paths).props(), "round-robin-group1")
for (_ ← 1 to iterationCount; _ ← 1 to connectionCount) {
- val id = Await.result((actor ? "hit").mapTo[String], timeout.duration)
+ val id: String = Await.result((actor ? "hit").mapTo[String], timeout.duration)
replies = replies + (id → (replies(id) + 1))
}
@@ -155,14 +155,14 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
var replies = Map.empty[String, Int].withDefaultValue(0)
- val actor = system.actorOf(Props(new Actor {
+ val actor: akka.actor.ActorRef = system.actorOf(Props(new Actor {
var n = 0
- var router = Router(RoundRobinRoutingLogic())
+ var router: akka.routing.Router = Router(RoundRobinRoutingLogic())
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case p: Props ⇒
n += 1
- val c = context.actorOf(p, name = "child-" + n)
+ val c: akka.actor.ActorRef = context.actorOf(p, name = "child-" + n)
context.watch(c)
router = router.addRoutee(c)
case Terminated(c) ⇒
@@ -173,8 +173,8 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
}
}))
- val childProps = Props(new Actor {
- def receive = {
+ val childProps: akka.actor.Props = Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "hit" ⇒ sender() ! self.path.name
case "end" ⇒ context.stop(self)
}
@@ -183,7 +183,7 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
(1 to connectionCount) foreach { _ ⇒ actor ! childProps }
for (_ ← 1 to iterationCount; _ ← 1 to connectionCount) {
- val id = Await.result((actor ? "hit").mapTo[String], timeout.duration)
+ val id: String = Await.result((actor ? "hit").mapTo[String], timeout.duration)
replies = replies + (id → (replies(id) + 1))
}
diff --git a/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala
index 24434da..210faf7 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala
@@ -19,7 +19,7 @@ class RouteeCreationSpec extends AkkaSpec {
val N = 100
system.actorOf(RoundRobinPool(N).props(Props(new Actor {
system.actorSelection(self.path).tell(Identify(self.path), testActor)
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
})))
for (i ← 1 to N) {
expectMsgType[ActorIdentity] match {
@@ -33,11 +33,11 @@ class RouteeCreationSpec extends AkkaSpec {
val N = 100
system.actorOf(RoundRobinPool(N).props(Props(new Actor {
context.parent ! "one"
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "one" ⇒ testActor forward "two"
}
})))
- val gotit = receiveWhile(messages = N) {
+ val gotit: scala.collection.immutable.Seq[String] = receiveWhile(messages = N) {
case "two" ⇒ lastSender.toString
}
expectNoMsg(100.millis)
diff --git a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala
index 231ddc5..bab6396 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala
@@ -35,11 +35,11 @@ object RoutingSpec {
"""
class TestActor extends Actor {
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
class Echo extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case _ ⇒ sender() ! self
}
}
@@ -47,7 +47,7 @@ object RoutingSpec {
}
class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with ImplicitSender {
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
import RoutingSpec._
muteDeadLetters(classOf[akka.dispatch.sysmsg.DeathWatchNotification])()
@@ -55,7 +55,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
"routers in general" must {
"evict terminated routees" in {
- val router = system.actorOf(RoundRobinPool(2).props(routeeProps = Props[Echo]))
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(2).props(routeeProps = Props[Echo]))
router ! ""
router ! ""
val c1, c2 = expectMsgType[ActorRef]
@@ -67,7 +67,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
awaitCond {
router ! ""
router ! ""
- val res = receiveWhile(100 millis, messages = 2) {
+ val res: scala.collection.immutable.Seq[akka.actor.ActorRef] = receiveWhile(100 millis, messages = 2) {
case x: ActorRef ⇒ x
}
res == Seq(c1, c1)
@@ -77,20 +77,20 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"not terminate when resizer is used" in {
- val latch = TestLatch(1)
- val resizer = new Resizer {
+ val latch: akka.testkit.TestLatch = TestLatch(1)
+ val resizer: akka.routing.Resizer = new Resizer {
def isTimeForResize(messageCounter: Long): Boolean = messageCounter == 0
def resize(currentRoutees: immutable.IndexedSeq[Routee]): Int = {
latch.countDown()
2
}
}
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
routeeProps = Props[TestActor]))
watch(router)
Await.ready(latch, remainingOrDefault)
router ! GetRoutees
- val routees = expectMsgType[Routees].routees
+ val routees: scala.collection.immutable.IndexedSeq[akka.routing.Routee] = expectMsgType[Routees].routees
routees.size should ===(2)
routees foreach { _.send(PoisonPill, testActor) }
// expect no Terminated
@@ -98,7 +98,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"use configured nr-of-instances when FromConfig" in {
- val router = system.actorOf(FromConfig.props(routeeProps = Props[TestActor]), "router1")
+ val router: akka.actor.ActorRef = system.actorOf(FromConfig.props(routeeProps = Props[TestActor]), "router1")
router ! GetRoutees
expectMsgType[Routees].routees.size should ===(3)
watch(router)
@@ -107,22 +107,22 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"use configured nr-of-instances when router is specified" in {
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 2).props(routeeProps = Props[TestActor]), "router2")
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 2).props(routeeProps = Props[TestActor]), "router2")
router ! GetRoutees
expectMsgType[Routees].routees.size should ===(3)
system.stop(router)
}
"use specified resizer when resizer not configured" in {
- val latch = TestLatch(1)
- val resizer = new Resizer {
+ val latch: akka.testkit.TestLatch = TestLatch(1)
+ val resizer: akka.routing.Resizer = new Resizer {
def isTimeForResize(messageCounter: Long): Boolean = messageCounter == 0
def resize(currentRoutees: immutable.IndexedSeq[Routee]): Int = {
latch.countDown()
3
}
}
- val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(
routeeProps = Props[TestActor]), "router3")
Await.ready(latch, remainingOrDefault)
router ! GetRoutees
@@ -132,12 +132,12 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
"set supplied supervisorStrategy" in {
//#supervision
- val escalator = OneForOneStrategy() {
+ val escalator: akka.actor.OneForOneStrategy = OneForOneStrategy() {
//#custom-strategy
case e ⇒ testActor ! e; SupervisorStrategy.Escalate
//#custom-strategy
}
- val router = system.actorOf(RoundRobinPool(1, supervisorStrategy = escalator).props(
+ val router: akka.actor.ActorRef = system.actorOf(RoundRobinPool(1, supervisorStrategy = escalator).props(
routeeProps = Props[TestActor]))
//#supervision
router ! GetRoutees
@@ -146,7 +146,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
expectMsgType[ActorKilledException]
- val router2 = system.actorOf(RoundRobinPool(1).withSupervisorStrategy(escalator).props(
+ val router2: akka.actor.ActorRef = system.actorOf(RoundRobinPool(1).withSupervisorStrategy(escalator).props(
routeeProps = Props[TestActor]))
router2 ! GetRoutees
EventFilter[ActorKilledException](occurrences = 1) intercept {
@@ -156,10 +156,10 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"set supplied supervisorStrategy for FromConfig" in {
- val escalator = OneForOneStrategy() {
+ val escalator: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case e ⇒ testActor ! e; SupervisorStrategy.Escalate
}
- val router = system.actorOf(FromConfig.withSupervisorStrategy(escalator).props(
+ val router: akka.actor.ActorRef = system.actorOf(FromConfig.withSupervisorStrategy(escalator).props(
routeeProps = Props[TestActor]), "router1")
router ! GetRoutees
EventFilter[ActorKilledException](occurrences = 1) intercept {
@@ -169,17 +169,17 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"default to all-for-one-always-escalate strategy" in {
- val restarter = OneForOneStrategy() {
+ val restarter: akka.actor.OneForOneStrategy = OneForOneStrategy() {
case e ⇒ testActor ! e; SupervisorStrategy.Restart
}
- val supervisor = system.actorOf(Props(new Supervisor(restarter)))
+ val supervisor: akka.actor.ActorRef = system.actorOf(Props(new Supervisor(restarter)))
supervisor ! RoundRobinPool(3).props(routeeProps = Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case x: String ⇒ throw new Exception(x)
}
override def postRestart(reason: Throwable): Unit = testActor ! "restarted"
}))
- val router = expectMsgType[ActorRef]
+ val router: akka.actor.ActorRef = expectMsgType[ActorRef]
EventFilter[Exception]("die", occurrences = 1) intercept {
router ! "die"
}
@@ -191,7 +191,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
"start in-line for context.actorOf()" in {
system.actorOf(Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "start" ⇒
context.actorOf(RoundRobinPool(2).props(routeeProps = Props(new Actor {
def receive = { case x ⇒ sender() ! x }
@@ -207,12 +207,12 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
"send message to connection" in {
class Actor1 extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case msg ⇒ testActor forward msg
}
}
- val routedActor = system.actorOf(NoRouter.props(routeeProps = Props(new Actor1)))
+ val routedActor: akka.actor.ActorRef = system.actorOf(NoRouter.props(routeeProps = Props(new Actor1)))
routedActor ! "hello"
routedActor ! "end"
@@ -223,14 +223,14 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
"router FromConfig" must {
"throw suitable exception when not configured" in {
- val e = intercept[ConfigurationException] {
+ val e: akka.ConfigurationException = intercept[ConfigurationException] {
system.actorOf(FromConfig.props(routeeProps = Props[TestActor]), "routerNotDefined")
}
e.getMessage should include("routerNotDefined")
}
"allow external configuration" in {
- val sys = ActorSystem("FromConfig", ConfigFactory
+ val sys: akka.actor.ActorSystem = ActorSystem("FromConfig", ConfigFactory
.parseString("akka.actor.deployment./routed.router=round-robin-pool")
.withFallback(system.settings.config))
try {
diff --git a/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala
index c675aaf..2163081 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala
@@ -16,14 +16,14 @@ import akka.testkit.TestProbe
object ScatterGatherFirstCompletedSpec {
class TestActor extends Actor {
- def receive = { case _ ⇒ }
+ def receive: PartialFunction[Any, Unit] = { case _ ⇒ }
}
final case class Stop(id: Option[Int] = None)
- def newActor(id: Int, shudownLatch: Option[TestLatch] = None)(implicit system: ActorSystem) =
+ def newActor(id: Int, shudownLatch: Option[TestLatch] = None)(implicit system: ActorSystem): akka.actor.ActorRef =
system.actorOf(Props(new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Stop(None) ⇒ context.stop(self)
case Stop(Some(_id)) if (_id == id) ⇒ context.stop(self)
case _id: Int if (_id == id) ⇒
@@ -33,7 +33,7 @@ object ScatterGatherFirstCompletedSpec {
}
}
- override def postStop = {
+ override def postStop: Unit = {
shudownLatch foreach (_.countDown())
}
}), "Actor:" + id)
@@ -45,26 +45,26 @@ class ScatterGatherFirstCompletedSpec extends AkkaSpec with DefaultTimeout with
"Scatter-gather group" must {
"deliver a broadcast message using the !" in {
- val doneLatch = new TestLatch(2)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(2)
- val counter1 = new AtomicInteger
- val actor1 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter1: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor1: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter1.addAndGet(msg)
}
}))
- val counter2 = new AtomicInteger
- val actor2 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter2: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter2.addAndGet(msg)
}
}))
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(ScatterGatherFirstCompletedGroup(paths, within = 1.second).props())
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(ScatterGatherFirstCompletedGroup(paths, within = 1.second).props())
routedActor ! Broadcast(1)
routedActor ! Broadcast("end")
@@ -75,11 +75,11 @@ class ScatterGatherFirstCompletedSpec extends AkkaSpec with DefaultTimeout with
}
"return response, even if one of the actors has stopped" in {
- val shutdownLatch = new TestLatch(1)
- val actor1 = newActor(1, Some(shutdownLatch))
- val actor2 = newActor(14, Some(shutdownLatch))
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(ScatterGatherFirstCompletedGroup(paths, within = 3.seconds).props())
+ val shutdownLatch: akka.testkit.TestLatch = new TestLatch(1)
+ val actor1: akka.actor.ActorRef = newActor(1, Some(shutdownLatch))
+ val actor2: akka.actor.ActorRef = newActor(14, Some(shutdownLatch))
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(ScatterGatherFirstCompletedGroup(paths, within = 3.seconds).props())
routedActor ! Broadcast(Stop(Some(1)))
Await.ready(shutdownLatch, TestLatch.DefaultTimeout)
@@ -91,8 +91,8 @@ class ScatterGatherFirstCompletedSpec extends AkkaSpec with DefaultTimeout with
"Scatter-gather pool" must {
"without routees should reply immediately" in {
- val probe = TestProbe()
- val router = system.actorOf(ScatterGatherFirstCompletedPool(nrOfInstances = 0, within = 5.seconds).props(Props.empty))
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val router: akka.actor.ActorRef = system.actorOf(ScatterGatherFirstCompletedPool(nrOfInstances = 0, within = 5.seconds).props(Props.empty))
router.tell("hello", probe.ref)
probe.expectMsgType[Status.Failure](2.seconds).cause.getClass should be(classOf[TimeoutException])
}
diff --git a/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala
index 38b5f26..67020f9 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala
@@ -14,9 +14,9 @@ class SmallestMailboxSpec extends AkkaSpec("akka.actor.serialize-messages = off"
"smallest mailbox pool" must {
"deliver messages to idle actor" in {
- val usedActors = new ConcurrentHashMap[Int, String]()
- val router = system.actorOf(SmallestMailboxPool(3).props(routeeProps = Props(new Actor {
- def receive = {
+ val usedActors: java.util.concurrent.ConcurrentHashMap[Int, String] = new ConcurrentHashMap[Int, String]()
+ val router: akka.actor.ActorRef = system.actorOf(SmallestMailboxPool(3).props(routeeProps = Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case (busy: TestLatch, receivedLatch: TestLatch) ⇒
usedActors.put(0, self.path.toString)
self ! "another in busy mailbox"
@@ -29,31 +29,31 @@ class SmallestMailboxSpec extends AkkaSpec("akka.actor.serialize-messages = off"
}
})))
- val busy = TestLatch(1)
- val received0 = TestLatch(1)
+ val busy: akka.testkit.TestLatch = TestLatch(1)
+ val received0: akka.testkit.TestLatch = TestLatch(1)
router ! ((busy, received0))
Await.ready(received0, TestLatch.DefaultTimeout)
- val received1 = TestLatch(1)
+ val received1: akka.testkit.TestLatch = TestLatch(1)
router ! ((1, received1))
Await.ready(received1, TestLatch.DefaultTimeout)
- val received2 = TestLatch(1)
+ val received2: akka.testkit.TestLatch = TestLatch(1)
router ! ((2, received2))
Await.ready(received2, TestLatch.DefaultTimeout)
- val received3 = TestLatch(1)
+ val received3: akka.testkit.TestLatch = TestLatch(1)
router ! ((3, received3))
Await.ready(received3, TestLatch.DefaultTimeout)
busy.countDown()
- val busyPath = usedActors.get(0)
+ val busyPath: String = usedActors.get(0)
busyPath should not be (null)
- val path1 = usedActors.get(1)
- val path2 = usedActors.get(2)
- val path3 = usedActors.get(3)
+ val path1: String = usedActors.get(1)
+ val path2: String = usedActors.get(2)
+ val path3: String = usedActors.get(3)
path1 should not be (busyPath)
path2 should not be (busyPath)
diff --git a/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala
index a7887b8..676381e 100644
--- a/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala
@@ -12,11 +12,11 @@ import akka.pattern.{ AskTimeoutException, ask }
import akka.testkit._
object TailChoppingSpec {
- def newActor(id: Int, sleepTime: Duration)(implicit system: ActorSystem) =
+ def newActor(id: Int, sleepTime: Duration)(implicit system: ActorSystem): akka.actor.ActorRef =
system.actorOf(Props(new Actor {
var times: Int = _
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case "stop" ⇒ context.stop(self)
case "times" ⇒ sender() ! times
case x ⇒
@@ -31,39 +31,39 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender
import TailChoppingSpec._
def oneOfShouldEqual(what: Any, default: Any, ref: ActorRef*)(f: ActorRef ⇒ Any) {
- val results = ref.map(p ⇒ f(p))
+ val results: Seq[Any] = ref.map(p ⇒ f(p))
results.count(_ == what) should equal(1)
results.count(_ == default) should equal(results.size - 1)
}
def allShouldEqual(what: Any, ref: ActorRef*)(f: ActorRef ⇒ Any) {
- val results = ref.map(p ⇒ f(p))
+ val results: Seq[Any] = ref.map(p ⇒ f(p))
results.count(_ == what) should equal(results.size)
}
"Tail-chopping group" must {
"deliver a broadcast message using the !" in {
- val doneLatch = new TestLatch(2)
+ val doneLatch: akka.testkit.TestLatch = new TestLatch(2)
- val counter1 = new AtomicInteger
- val actor1 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter1: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor1: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter1.addAndGet(msg)
}
}))
- val counter2 = new AtomicInteger
- val actor2 = system.actorOf(Props(new Actor {
- def receive = {
+ val counter2: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val actor2: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case "end" ⇒ doneLatch.countDown()
case msg: Int ⇒ counter2.addAndGet(msg)
}
}))
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(TailChoppingGroup(paths, within = 1.second, interval = 100.millisecond).props())
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(TailChoppingGroup(paths, within = 1.second, interval = 100.millisecond).props())
routedActor ! Broadcast(1)
routedActor ! Broadcast("end")
@@ -74,11 +74,11 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender
}
"return response from second actor after inactivity from first one" in {
- val actor1 = newActor(1, 1.millis)
- val actor2 = newActor(2, 1.millis)
- val probe = TestProbe()
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(TailChoppingGroup(paths, within = 1.seconds, interval = 50.millisecond).props())
+ val actor1: akka.actor.ActorRef = newActor(1, 1.millis)
+ val actor2: akka.actor.ActorRef = newActor(2, 1.millis)
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(TailChoppingGroup(paths, within = 1.seconds, interval = 50.millisecond).props())
probe.send(routedActor, "")
probe.expectMsg("ack")
@@ -89,11 +89,11 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender
}
"throw exception if no result will arrive within given time" in {
- val actor1 = newActor(3, 500.millis)
- val actor2 = newActor(4, 500.millis)
- val probe = TestProbe()
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(TailChoppingGroup(paths, within = 300.milliseconds,
+ val actor1: akka.actor.ActorRef = newActor(3, 500.millis)
+ val actor2: akka.actor.ActorRef = newActor(4, 500.millis)
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(TailChoppingGroup(paths, within = 300.milliseconds,
interval = 50.milliseconds).props())
probe.send(routedActor, "")
@@ -107,11 +107,11 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender
}
"reply ASAP" in {
- val actor1 = newActor(5, 1.seconds)
- val actor2 = newActor(6, 4.seconds)
- val probe = TestProbe()
- val paths = List(actor1, actor2).map(_.path.toString)
- val routedActor = system.actorOf(TailChoppingGroup(paths, within = 5.seconds, interval = 100.milliseconds).props())
+ val actor1: akka.actor.ActorRef = newActor(5, 1.seconds)
+ val actor2: akka.actor.ActorRef = newActor(6, 4.seconds)
+ val probe: akka.testkit.TestProbe = TestProbe()
+ val paths: List[String] = List(actor1, actor2).map(_.path.toString)
+ val routedActor: akka.actor.ActorRef = system.actorOf(TailChoppingGroup(paths, within = 5.seconds, interval = 100.milliseconds).props())
probe.send(routedActor, "")
probe.expectMsg(max = 2.seconds, "ack")
diff --git a/akka-actor-tests/src/test/scala/akka/serialization/DisabledJavaSerializerWarningSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/DisabledJavaSerializerWarningSpec.scala
index 22e136c..97398f3 100644
--- a/akka-actor-tests/src/test/scala/akka/serialization/DisabledJavaSerializerWarningSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/serialization/DisabledJavaSerializerWarningSpec.scala
@@ -30,7 +30,7 @@ class DisabledJavaSerializerWarningSpec extends AkkaSpec(
"be logged for suspicious messages" in {
EventFilter.warning(start = "Outgoing message attempted to use Java Serialization", occurrences = 1).intercept {
- val echo = system.actorOf(TestActors.echoActorProps)
+ val echo: akka.actor.ActorRef = system.actorOf(TestActors.echoActorProps)
echo ! List("a")
expectNoMsg(300.millis)
}
@@ -39,7 +39,7 @@ class DisabledJavaSerializerWarningSpec extends AkkaSpec(
"be skipped for well known local messages" in {
EventFilter.warning(start = "Outgoing message attempted to use Java Serialization", occurrences = 0).intercept {
- val echo = system.actorOf(TestActors.echoActorProps)
+ val echo: akka.actor.ActorRef = system.actorOf(TestActors.echoActorProps)
echo ! Msg("a") // Msg is in the akka package
expectMsg(Msg("a"))
}
@@ -48,9 +48,9 @@ class DisabledJavaSerializerWarningSpec extends AkkaSpec(
"log and throw exception for erroneous incoming messages when Java Serialization is off" in {
EventFilter.warning(start = "Incoming message attempted to use Java Serialization", occurrences = 1).intercept {
intercept[DisabledJavaSerializer.JavaSerializationException] {
- val byteBuffer = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN)
- val esys = system.asInstanceOf[ExtendedActorSystem]
- val dser = DisabledJavaSerializer(esys)
+ val byteBuffer: java.nio.ByteBuffer = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN)
+ val esys: akka.actor.ExtendedActorSystem = system.asInstanceOf[ExtendedActorSystem]
+ val dser: akka.serialization.DisabledJavaSerializer = DisabledJavaSerializer(esys)
dser.fromBinary(byteBuffer, "")
}
}
diff --git a/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala
index adc4161..160b518 100644
--- a/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala
@@ -29,30 +29,30 @@ final class FakeSerializer extends Serializer {
private val registry = new ConcurrentHashMap[Integer, AnyRef]()
private val counter = new AtomicInteger(0)
- def toBinary(o: AnyRef) = {
- val id = counter.addAndGet(1)
+ def toBinary(o: AnyRef): Array[Byte] = {
+ val id: Int = counter.addAndGet(1)
require(id < Byte.MaxValue)
registry.put(id, o)
Array(id.toByte)
}
- def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]) = {
+ def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = {
require(bytes.length == 1)
- val id = bytes(0).toInt
+ val id: Int = bytes(0).toInt
registry.get(id)
}
}
object SerializationSetupSpec {
- val programmaticDummySerializer = new FakeSerializer
- val testSerializer = new NoopSerializer
+ val programmaticDummySerializer: akka.serialization.FakeSerializer = new FakeSerializer
+ val testSerializer: akka.serialization.NoopSerializer = new NoopSerializer
- val serializationSettings = SerializationSetup { _ ⇒
+ val serializationSettings: akka.serialization.SerializationSetup = SerializationSetup { _ ⇒
List(
SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy])))
}
- val bootstrapSettings = BootstrapSetup(None, Some(ConfigFactory.parseString("""
+ val bootstrapSettings: akka.actor.BootstrapSetup = BootstrapSetup(None, Some(ConfigFactory.parseString("""
akka {
actor {
serialize-messages = off
@@ -66,9 +66,9 @@ object SerializationSetupSpec {
}
}
""")), None)
- val actorSystemSettings = ActorSystemSetup(bootstrapSettings, serializationSettings)
+ val actorSystemSettings: akka.actor.setup.ActorSystemSetup = ActorSystemSetup(bootstrapSettings, serializationSettings)
- val noJavaSerializationSystem = ActorSystem("SerializationSettingsSpec" + "NoJavaSerialization", ConfigFactory.parseString(
+ val noJavaSerializationSystem: akka.actor.ActorSystem = ActorSystem("SerializationSettingsSpec" + "NoJavaSerialization", ConfigFactory.parseString(
"""
akka {
actor {
@@ -78,7 +78,7 @@ object SerializationSetupSpec {
}
}
""".stripMargin))
- val noJavaSerializer = new DisabledJavaSerializer(noJavaSerializationSystem.asInstanceOf[ExtendedActorSystem])
+ val noJavaSerializer: akka.serialization.DisabledJavaSerializer = new DisabledJavaSerializer(noJavaSerializationSystem.asInstanceOf[ExtendedActorSystem])
}
@@ -90,12 +90,12 @@ class SerializationSetupSpec extends AkkaSpec(
"The serialization settings" should {
"allow for programmatic configuration of serializers" in {
- val serializer = SerializationExtension(system).findSerializerFor(new ProgrammaticDummy)
+ val serializer: akka.serialization.Serializer = SerializationExtension(system).findSerializerFor(new ProgrammaticDummy)
serializer shouldBe theSameInstanceAs(programmaticDummySerializer)
}
"allow a configured binding to hook up to a programmatic serializer" in {
- val serializer = SerializationExtension(system).findSerializerFor(new ConfigurationDummy)
+ val serializer: akka.serialization.Serializer = SerializationExtension(system).findSerializerFor(new ConfigurationDummy)
serializer shouldBe theSameInstanceAs(programmaticDummySerializer)
}
@@ -105,12 +105,12 @@ class SerializationSetupSpec extends AkkaSpec(
// that they'd need a different actor system to be able to create it... someone MAY pick a system with
// allow-java-serialization=on to create the SerializationSetup and use that SerializationSetup
// in another system with allow-java-serialization=off
- val addedJavaSerializationSettings = SerializationSetup { _ ⇒
+ val addedJavaSerializationSettings: akka.serialization.SerializationSetup = SerializationSetup { _ ⇒
List(
SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy])),
SerializerDetails("java-manual", new JavaSerializer(system.asInstanceOf[ExtendedActorSystem]), List(classOf[ProgrammaticJavaDummy])))
}
- val addedJavaSerializationProgramaticallyButDisabledSettings = BootstrapSetup(None, Some(ConfigFactory.parseString("""
+ val addedJavaSerializationProgramaticallyButDisabledSettings: akka.actor.BootstrapSetup = BootstrapSetup(None, Some(ConfigFactory.parseString("""
akka {
loglevel = debug
actor {
@@ -121,7 +121,7 @@ class SerializationSetupSpec extends AkkaSpec(
}
""")), None)
- val addedJavaSerializationViaSettingsSystem =
+ val addedJavaSerializationViaSettingsSystem: akka.actor.ActorSystem =
ActorSystem(
"addedJavaSerializationSystem",
ActorSystemSetup(
@@ -141,7 +141,7 @@ class SerializationSetupSpec extends AkkaSpec(
}
"have replaced java serializer" in {
- val p = TestProbe()(addedJavaSerializationViaSettingsSystem) // only receiver has the serialization disabled
+ val p: akka.testkit.TestProbe = TestProbe()(addedJavaSerializationViaSettingsSystem) // only receiver has the serialization disabled
p.ref ! new ProgrammaticJavaDummy
SerializationExtension(system).findSerializerFor(new ProgrammaticJavaDummy).toBinary(new ProgrammaticJavaDummy)
@@ -153,13 +153,13 @@ class SerializationSetupSpec extends AkkaSpec(
}
"disable java serialization also for incoming messages if serializer id usually would have found the serializer" in {
- val ser1 = SerializationExtension(system)
- val msg = new SerializableDummy
- val bytes = ser1.serialize(msg).get
- val serId = ser1.findSerializerFor(msg).identifier
+ val ser1: akka.serialization.Serialization = SerializationExtension(system)
+ val msg: java.util.Date = new SerializableDummy
+ val bytes: Array[Byte] = ser1.serialize(msg).get
+ val serId: Int = ser1.findSerializerFor(msg).identifier
ser1.findSerializerFor(msg).includeManifest should ===(false)
- val ser2 = SerializationExtension(noJavaSerializationSystem)
+ val ser2: akka.serialization.Serialization = SerializationExtension(noJavaSerializationSystem)
ser2.findSerializerFor(new SerializableDummy) should ===(noJavaSerializer)
ser2.serializerByIdentity(serId) should ===(noJavaSerializer)
intercept[DisabledJavaSerializer.JavaSerializationException] {
diff --git a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala
index 9a5838f..c07024c 100644
--- a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala
@@ -22,7 +22,7 @@ import test.akka.serialization.NoVerification
object SerializationTests {
- val serializeConf = s"""
+ val serializeConf: String = s"""
akka {
actor {
serialize-messages = off
@@ -81,7 +81,7 @@ object SerializationTests {
"""
class FooActor extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case s: String ⇒ sender() ! s
}
}
@@ -92,15 +92,15 @@ object SerializationTests {
}
class NonSerializableActor(system: ActorSystem) extends Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case s: String ⇒ sender() ! s
}
}
def mostlyReferenceSystem: ActorSystem = {
- val referenceConf = ConfigFactory.defaultReference()
+ val referenceConf: com.typesafe.config.Config = ConfigFactory.defaultReference()
// we are checking the old Java serialization formats here
- val mostlyReferenceConf = ConfigFactory.parseString("""
+ val mostlyReferenceConf: com.typesafe.config.Config = ConfigFactory.parseString("""
akka.actor.enable-additional-serialization-bindings = off
""").withFallback(AkkaSpec.testConf.withFallback(referenceConf))
ActorSystem("SerializationSystem", mostlyReferenceConf)
@@ -120,7 +120,7 @@ object SerializationTests {
}
"""
- val systemMessageClasses = List[Class[_]](
+ val systemMessageClasses: List[Class[_]] = List[Class[_]](
classOf[Create],
classOf[Recreate],
classOf[Suspend],
@@ -136,11 +136,11 @@ object SerializationTests {
class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
import SerializationTests._
- val ser = SerializationExtension(system)
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
import ser._
- val addr = Address("120", "Monroe Street", "Santa Clara", "95050")
- val person = Person("debasish ghosh", 25, Address("120", "Monroe Street", "Santa Clara", "95050"))
+ val addr: akka.serialization.SerializationTests.Address = Address("120", "Monroe Street", "Santa Clara", "95050")
+ val person: akka.serialization.SerializationTests.Person = Person("debasish ghosh", 25, Address("120", "Monroe Street", "Santa Clara", "95050"))
"Serialization" must {
@@ -158,13 +158,13 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
}
"serialize record with default serializer" in {
- val r = Record(100, person)
+ val r: akka.serialization.SerializationTests.Record = Record(100, person)
assert(deserialize(serialize(r).get, classOf[Record]).get === r)
}
"not serialize ActorCell" in {
- val a = system.actorOf(Props(new Actor {
- def receive = {
+ val a: akka.actor.ActorRef = system.actorOf(Props(new Actor {
+ def receive: PartialFunction[Any, Unit] = {
case o: ObjectOutputStream ⇒
try o.writeObject(this) catch { case _: NotSerializableException ⇒ testActor ! "pass" }
}
@@ -175,17 +175,17 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
}
"serialize DeadLetterActorRef" in {
- val outbuf = new ByteArrayOutputStream()
- val out = new ObjectOutputStream(outbuf)
- val a = ActorSystem("SerializeDeadLeterActorRef", AkkaSpec.testConf)
+ val outbuf: java.io.ByteArrayOutputStream = new ByteArrayOutputStream()
+ val out: java.io.ObjectOutputStream = new ObjectOutputStream(outbuf)
+ val a: akka.actor.ActorSystem = ActorSystem("SerializeDeadLeterActorRef", AkkaSpec.testConf)
try {
out.writeObject(a.deadLetters)
out.flush()
out.close()
- val in = new ObjectInputStream(new ByteArrayInputStream(outbuf.toByteArray))
+ val in: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(outbuf.toByteArray))
JavaSerializer.currentSystem.withValue(a.asInstanceOf[ActorSystemImpl]) {
- val deadLetters = in.readObject().asInstanceOf[DeadLetterActorRef]
+ val deadLetters: akka.actor.DeadLetterActorRef = in.readObject().asInstanceOf[DeadLetterActorRef]
(deadLetters eq a.deadLetters) should ===(true)
}
} finally {
@@ -244,7 +244,7 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
}
"use ByteArraySerializer for byte arrays" in {
- val byteSerializer = ser.serializerFor(classOf[Array[Byte]])
+ val byteSerializer: akka.serialization.Serializer = ser.serializerFor(classOf[Array[Byte]])
byteSerializer.getClass should be theSameInstanceAs classOf[ByteArraySerializer]
for (a ← Seq("foo".getBytes("UTF-8"), null: Array[Byte], Array[Byte]()))
@@ -256,15 +256,15 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
}
"support ByteBuffer serialization for byte arrays" in {
- val byteSerializer = ser.serializerFor(classOf[Array[Byte]]).asInstanceOf[ByteBufferSerializer]
+ val byteSerializer: akka.serialization.ByteBufferSerializer = ser.serializerFor(classOf[Array[Byte]]).asInstanceOf[ByteBufferSerializer]
- val byteBuffer = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN)
+ val byteBuffer: java.nio.ByteBuffer = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN)
val str = "abcdef"
- val payload = str.getBytes("UTF-8")
+ val payload: Array[Byte] = str.getBytes("UTF-8")
byteSerializer.toBinary(payload, byteBuffer)
byteBuffer.position() should ===(payload.length)
byteBuffer.flip()
- val deserialized = byteSerializer.fromBinary(byteBuffer, "").asInstanceOf[Array[Byte]]
+ val deserialized: Array[Byte] = byteSerializer.fromBinary(byteBuffer, "").asInstanceOf[Array[Byte]]
byteBuffer.remaining() should ===(0)
new String(deserialized, "UTF-8") should ===(str)
@@ -277,7 +277,7 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
class VerifySerializabilitySpec extends AkkaSpec(SerializationTests.verifySerializabilityConf) {
import SerializationTests._
- implicit val timeout = Timeout(5 seconds)
+ implicit val timeout: akka.util.Timeout = Timeout(5 seconds)
"verify config" in {
system.settings.SerializeAllCreators should ===(true)
@@ -285,20 +285,20 @@ class VerifySerializabilitySpec extends AkkaSpec(SerializationTests.verifySerial
}
"verify creators" in {
- val a = system.actorOf(Props[FooActor])
+ val a: akka.actor.ActorRef = system.actorOf(Props[FooActor])
system stop a
- val b = system.actorOf(Props(new FooAbstractActor))
+ val b: akka.actor.ActorRef = system.actorOf(Props(new FooAbstractActor))
system stop b
intercept[IllegalArgumentException] {
- val d = system.actorOf(Props(new NonSerializableActor(system)))
+ val d: akka.actor.ActorRef = system.actorOf(Props(new NonSerializableActor(system)))
}
}
"verify messages" in {
- val a = system.actorOf(Props[FooActor])
+ val a: akka.actor.ActorRef = system.actorOf(Props[FooActor])
Await.result(a ? "pigdog", timeout.duration) should ===("pigdog")
EventFilter[NotSerializableException](occurrences = 1) intercept {
@@ -311,8 +311,8 @@ class VerifySerializabilitySpec extends AkkaSpec(SerializationTests.verifySerial
class ReferenceSerializationSpec extends AkkaSpec(SerializationTests.mostlyReferenceSystem) {
import SerializationTests._
- val ser = SerializationExtension(system)
- def serializerMustBe(toSerialize: Class[_], expectedSerializer: Class[_]) =
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
+ def serializerMustBe(toSerialize: Class[_], expectedSerializer: Class[_]): org.scalatest.Assertion =
ser.serializerFor(toSerialize).getClass should ===(expectedSerializer)
"Serialization settings from reference.conf" must {
@@ -334,11 +334,11 @@ class ReferenceSerializationSpec extends AkkaSpec(SerializationTests.mostlyRefer
}
"serialize function with JavaSerializer" in {
- val f = (i: Int) ⇒ i + 1
- val serializer = ser.serializerFor(f.getClass)
+ val f: Int ⇒ Int = (i: Int) ⇒ i + 1
+ val serializer: akka.serialization.Serializer = ser.serializerFor(f.getClass)
serializer.getClass should ===(classOf[JavaSerializer])
- val bytes = ser.serialize(f).get
- val f2 = ser.deserialize(bytes, serializer.identifier, "").get.asInstanceOf[Function1[Int, Int]]
+ val bytes: Array[Byte] = ser.serialize(f).get
+ val f2: Int ⇒ Int = ser.deserialize(bytes, serializer.identifier, "").get.asInstanceOf[Function1[Int, Int]]
f2(3) should ===(4)
}
@@ -347,13 +347,13 @@ class ReferenceSerializationSpec extends AkkaSpec(SerializationTests.mostlyRefer
class SerializationCompatibilitySpec extends AkkaSpec(SerializationTests.mostlyReferenceSystem) {
- val ser = SerializationExtension(system)
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
"Cross-version serialization compatibility" must {
def verify(obj: SystemMessage, asExpected: String): Unit = {
- val bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(asExpected)
- val stream = new ObjectInputStream(new ByteArrayInputStream(bytes))
- val read = stream.readObject()
+ val bytes: Array[Byte] = javax.xml.bind.DatatypeConverter.parseHexBinary(asExpected)
+ val stream: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes))
+ val read: Object = stream.readObject()
read should ===(obj)
}
@@ -442,7 +442,7 @@ class SerializationCompatibilitySpec extends AkkaSpec(SerializationTests.mostlyR
class OverriddenSystemMessageSerializationSpec extends AkkaSpec(SerializationTests.systemMessageMultiSerializerConf) {
import SerializationTests._
- val ser = SerializationExtension(system)
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
"Overridden SystemMessage serialization" must {
@@ -460,7 +460,7 @@ class OverriddenSystemMessageSerializationSpec extends AkkaSpec(SerializationTes
class DefaultSerializationWarningSpec extends AkkaSpec(
ConfigFactory.parseString("akka.actor.warn-about-java-serializer-usage = on")) {
- val ser = SerializationExtension(system)
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
val messagePrefix = "Using the default Java serializer for class"
"Using the default Java serializer" must {
@@ -486,7 +486,7 @@ class NoVerificationWarningSpec extends AkkaSpec(
"akka.actor.warn-about-java-serializer-usage = on\n" +
"akka.actor.warn-on-no-serialization-verification = on")) {
- val ser = SerializationExtension(system)
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
val messagePrefix = "Using the default Java serializer for class"
"When warn-on-no-serialization-verification = on, using the default Java serializer" must {
@@ -510,7 +510,7 @@ class NoVerificationWarningOffSpec extends AkkaSpec(
"akka.actor.warn-about-java-serializer-usage = on\n" +
"akka.actor.warn-on-no-serialization-verification = off")) {
- val ser = SerializationExtension(system)
+ val ser: akka.serialization.Serialization = SerializationExtension(system)
val messagePrefix = "Using the default Java serializer for class"
"When warn-on-no-serialization-verification = off, using the default Java serializer" must {
diff --git a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala
index 73c5efd..a55dc05 100644
--- a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala
@@ -13,7 +13,7 @@ import akka.dispatch.MessageDispatcherConfigurator
object CallingThreadDispatcherModelSpec {
import ActorModelSpec._
- val config = {
+ val config: String = {
"""
boss {
executor = thread-pool-executor
@@ -44,7 +44,7 @@ object CallingThreadDispatcherModelSpec {
class CallingThreadDispatcherModelSpec extends ActorModelSpec(CallingThreadDispatcherModelSpec.config) {
import ActorModelSpec._
- val dispatcherCount = new AtomicInteger()
+ val dispatcherCount: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger()
override def interceptedDispatcher(): MessageDispatcherInterceptor = {
// use new id for each test, since the MessageDispatcherInterceptor holds state
diff --git a/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala b/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala
index d6ff811..9c9ff16 100644
--- a/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala
@@ -21,9 +21,9 @@ import scala.collection.mutable.Builder
class ByteStringSpec extends WordSpec with Matchers with Checkers {
- implicit val betterGeneratorDrivenConfig = PropertyCheckConfig().copy(minSuccessful = 1000)
+ implicit val betterGeneratorDrivenConfig: ByteStringSpec.this.PropertyCheckConfig = PropertyCheckConfig().copy(minSuccessful = 1000)
- def genSimpleByteString(min: Int, max: Int) = for {
+ def genSimpleByteString(min: Int, max: Int): org.scalacheck.Gen[akka.util.ByteString] = for {
n ← Gen.choose(min, max)
b ← Gen.containerOfN[Array, Byte](n, arbitrary[Byte])
from ← Gen.choose(0, b.length)
@@ -63,25 +63,25 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
}
def serialize(obj: AnyRef): Array[Byte] = {
- val os = new ByteArrayOutputStream
- val bos = new ObjectOutputStream(os)
+ val os: java.io.ByteArrayOutputStream = new ByteArrayOutputStream
+ val bos: java.io.ObjectOutputStream = new ObjectOutputStream(os)
bos.writeObject(obj)
os.toByteArray
}
def deserialize(bytes: Array[Byte]): AnyRef = {
- val is = new ObjectInputStream(new ByteArrayInputStream(bytes))
+ val is: java.io.ObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes))
is.readObject
}
- def testSer(obj: AnyRef) = {
+ def testSer(obj: AnyRef): Boolean = {
deserialize(serialize(obj)) == obj
}
- def hexFromSer(obj: AnyRef) = {
- val os = new ByteArrayOutputStream
- val bos = new ObjectOutputStream(os)
+ def hexFromSer(obj: AnyRef): String = {
+ val os: java.io.ByteArrayOutputStream = new ByteArrayOutputStream
+ val bos: java.io.ObjectOutputStream = new ObjectOutputStream(os)
bos.writeObject(obj)
String valueOf encodeHex(os.toByteArray)
}
@@ -113,19 +113,19 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
implicit val arbitraryByteStringBuilder: Arbitrary[ByteStringBuilder] = Arbitrary(ByteString.newBuilder)
def likeVector(bs: ByteString)(body: IndexedSeq[Byte] ⇒ Any): Boolean = {
- val vec = Vector(bs: _*)
+ val vec: scala.collection.immutable.Vector[Byte] = Vector(bs: _*)
body(bs) == body(vec)
}
def likeVectors(bsA: ByteString, bsB: ByteString)(body: (IndexedSeq[Byte], IndexedSeq[Byte]) ⇒ Any): Boolean = {
- val vecA = Vector(bsA: _*)
- val vecB = Vector(bsB: _*)
+ val vecA: scala.collection.immutable.Vector[Byte] = Vector(bsA: _*)
+ val vecB: scala.collection.immutable.Vector[Byte] = Vector(bsB: _*)
body(bsA, bsB) == body(vecA, vecB)
}
def likeVecIt(bs: ByteString)(body: BufferedIterator[Byte] ⇒ Any, strict: Boolean = true): Boolean = {
- val bsIterator = bs.iterator
- val vecIterator = Vector(bs: _*).iterator.buffered
+ val bsIterator: akka.util.ByteIterator = bs.iterator
+ val vecIterator: scala.collection.BufferedIterator[Byte] = Vector(bs: _*).iterator.buffered
(body(bsIterator) == body(vecIterator)) &&
(!strict || (bsIterator.toSeq == vecIterator.toSeq))
}
@@ -138,8 +138,8 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
}
def likeVecBld(body: Builder[Byte, _] ⇒ Unit): Boolean = {
- val bsBuilder = ByteString.newBuilder
- val vecBuilder = Vector.newBuilder[Byte]
+ val bsBuilder: akka.util.ByteStringBuilder = ByteString.newBuilder
+ val vecBuilder: scala.collection.mutable.Builder[Byte, scala.collection.immutable.Vector[Byte]] = Vector.newBuilder[Byte]
body(bsBuilder)
body(vecBuilder)
@@ -151,10 +151,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
val elemSize = 2
val (bytes, from, until) = slice
val (n, a, b) = (bytes.length / elemSize, from / elemSize, until / elemSize)
- val reference = new Array[Short](n)
+ val reference: Array[Short] = new Array[Short](n)
bytes.asByteBuffer.order(byteOrder).asShortBuffer.get(reference, 0, n)
- val input = bytes.iterator
- val decoded = new Array[Short](n)
+ val input: akka.util.ByteIterator = bytes.iterator
+ val decoded: Array[Short] = new Array[Short](n)
for (i ← 0 until a) decoded(i) = input.getShort(byteOrder)
input.getShorts(decoded, a, b - a)(byteOrder)
for (i ← b until n) decoded(i) = input.getShort(byteOrder)
@@ -165,10 +165,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
val elemSize = 4
val (bytes, from, until) = slice
val (n, a, b) = (bytes.length / elemSize, from / elemSize, until / elemSize)
- val reference = new Array[Int](n)
+ val reference: Array[Int] = new Array[Int](n)
bytes.asByteBuffer.order(byteOrder).asIntBuffer.get(reference, 0, n)
- val input = bytes.iterator
- val decoded = new Array[Int](n)
+ val input: akka.util.ByteIterator = bytes.iterator
+ val decoded: Array[Int] = new Array[Int](n)
for (i ← 0 until a) decoded(i) = input.getInt(byteOrder)
input.getInts(decoded, a, b - a)(byteOrder)
for (i ← b until n) decoded(i) = input.getInt(byteOrder)
@@ -179,10 +179,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
val elemSize = 8
val (bytes, from, until) = slice
val (n, a, b) = (bytes.length / elemSize, from / elemSize, until / elemSize)
- val reference = new Array[Long](n)
+ val reference: Array[Long] = new Array[Long](n)
bytes.asByteBuffer.order(byteOrder).asLongBuffer.get(reference, 0, n)
- val input = bytes.iterator
- val decoded = new Array[Long](n)
+ val input: akka.util.ByteIterator = bytes.iterator
+ val decoded: Array[Long] = new Array[Long](n)
for (i ← 0 until a) decoded(i) = input.getLong(byteOrder)
input.getLongs(decoded, a, b - a)(byteOrder)
for (i ← b until n) decoded(i) = input.getLong(byteOrder)
@@ -193,10 +193,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
val elemSize = 4
val (bytes, from, until) = slice
val (n, a, b) = (bytes.length / elemSize, from / elemSize, until / elemSize)
- val reference = new Array[Float](n)
+ val reference: Array[Float] = new Array[Float](n)
bytes.asByteBuffer.order(byteOrder).asFloatBuffer.get(reference, 0, n)
- val input = bytes.iterator
- val decoded = new Array[Float](n)
+ val input: akka.util.ByteIterator = bytes.iterator
+ val decoded: Array[Float] = new Array[Float](n)
for (i ← 0 until a) decoded(i) = input.getFloat(byteOrder)
input.getFloats(decoded, a, b - a)(byteOrder)
for (i ← b until n) decoded(i) = input.getFloat(byteOrder)
@@ -208,10 +208,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
val elemSize = 8
val (bytes, from, until) = slice
val (n, a, b) = (bytes.length / elemSize, from / elemSize, until / elemSize)
- val reference = new Array[Double](n)
+ val reference: Array[Double] = new Array[Double](n)
bytes.asByteBuffer.order(byteOrder).asDoubleBuffer.get(reference, 0, n)
- val input = bytes.iterator
- val decoded = new Array[Double](n)
+ val input: akka.util.ByteIterator = bytes.iterator
+ val decoded: Array[Double] = new Array[Double](n)
for (i ← 0 until a) decoded(i) = input.getDouble(byteOrder)
input.getDoubles(decoded, a, b - a)(byteOrder)
for (i ← b until n) decoded(i) = input.getDouble(byteOrder)
@@ -222,9 +222,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
def testShortEncoding(slice: ArraySlice[Short], byteOrder: ByteOrder): Boolean = {
val elemSize = 2
val (data, from, to) = slice
- val reference = new Array[Byte](data.length * elemSize)
+ val reference: Array[Byte] = new Array[Byte](data.length * elemSize)
ByteBuffer.wrap(reference).order(byteOrder).asShortBuffer.put(data)
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.putShort(data(i))(byteOrder)
builder.putShorts(data, from, to - from)(byteOrder)
for (i ← to until data.length) builder.putShort(data(i))(byteOrder)
@@ -234,9 +234,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
def testIntEncoding(slice: ArraySlice[Int], byteOrder: ByteOrder): Boolean = {
val elemSize = 4
val (data, from, to) = slice
- val reference = new Array[Byte](data.length * elemSize)
+ val reference: Array[Byte] = new Array[Byte](data.length * elemSize)
ByteBuffer.wrap(reference).order(byteOrder).asIntBuffer.put(data)
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.putInt(data(i))(byteOrder)
builder.putInts(data, from, to - from)(byteOrder)
for (i ← to until data.length) builder.putInt(data(i))(byteOrder)
@@ -246,9 +246,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
def testLongEncoding(slice: ArraySlice[Long], byteOrder: ByteOrder): Boolean = {
val elemSize = 8
val (data, from, to) = slice
- val reference = new Array[Byte](data.length * elemSize)
+ val reference: Array[Byte] = new Array[Byte](data.length * elemSize)
ByteBuffer.wrap(reference).order(byteOrder).asLongBuffer.put(data)
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.putLong(data(i))(byteOrder)
builder.putLongs(data, from, to - from)(byteOrder)
for (i ← to until data.length) builder.putLong(data(i))(byteOrder)
@@ -259,9 +259,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
val elemSize = 8
val (data, nBytes) = anb
- val reference = new Array[Byte](data.length * elemSize)
+ val reference: Array[Byte] = new Array[Byte](data.length * elemSize)
ByteBuffer.wrap(reference).order(byteOrder).asLongBuffer.put(data)
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until data.length) builder.putLongPart(data(i), nBytes)(byteOrder)
reference.zipWithIndex.collect({ // Since there is no partial put on LongBuffer, we need to collect only the interesting bytes
@@ -273,9 +273,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
def testFloatEncoding(slice: ArraySlice[Float], byteOrder: ByteOrder): Boolean = {
val elemSize = 4
val (data, from, to) = slice
- val reference = new Array[Byte](data.length * elemSize)
+ val reference: Array[Byte] = new Array[Byte](data.length * elemSize)
ByteBuffer.wrap(reference).order(byteOrder).asFloatBuffer.put(data)
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.putFloat(data(i))(byteOrder)
builder.putFloats(data, from, to - from)(byteOrder)
for (i ← to until data.length) builder.putFloat(data(i))(byteOrder)
@@ -285,9 +285,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
def testDoubleEncoding(slice: ArraySlice[Double], byteOrder: ByteOrder): Boolean = {
val elemSize = 8
val (data, from, to) = slice
- val reference = new Array[Byte](data.length * elemSize)
+ val reference: Array[Byte] = new Array[Byte](data.length * elemSize)
ByteBuffer.wrap(reference).order(byteOrder).asDoubleBuffer.put(data)
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.putDouble(data(i))(byteOrder)
builder.putDoubles(data, from, to - from)(byteOrder)
for (i ← to until data.length) builder.putDouble(data(i))(byteOrder)
@@ -408,7 +408,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
ByteStrings(ByteString1.fromString(""), ByteString1.fromString("a")).drop(2) should ===(ByteString(""))
ByteStrings(ByteString1.fromString(""), ByteString1.fromString("a")).drop(Int.MaxValue) should ===(ByteString(""))
- val bss = ByteStrings(Vector(
+ val bss: akka.util.ByteString = ByteStrings(Vector(
ByteString1.fromString("a"),
ByteString1.fromString("bc"),
ByteString1.fromString("def")))
@@ -450,7 +450,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
ByteStrings(ByteString1.fromString(""), ByteString1.fromString("a")).dropRight(2) should ===(ByteString(""))
ByteStrings(ByteString1.fromString(""), ByteString1.fromString("a")).dropRight(Int.MaxValue) should ===(ByteString(""))
- val bss = ByteStrings(Vector(
+ val bss: akka.util.ByteString = ByteStrings(Vector(
ByteString1.fromString("a"),
ByteString1.fromString("bc"),
ByteString1.fromString("def")))
@@ -529,13 +529,13 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
}
"indexOf" in {
ByteString.empty.indexOf(5) should ===(-1)
- val byteString1 = ByteString1.fromString("abc")
+ val byteString1: akka.util.ByteString.ByteString1 = ByteString1.fromString("abc")
byteString1.indexOf('a') should ===(0)
byteString1.indexOf('b') should ===(1)
byteString1.indexOf('c') should ===(2)
byteString1.indexOf('d') should ===(-1)
- val byteStrings = ByteStrings(ByteString1.fromString("abc"), ByteString1.fromString("efg"))
+ val byteStrings: akka.util.ByteString = ByteStrings(ByteString1.fromString("abc"), ByteString1.fromString("efg"))
byteStrings.indexOf('a') should ===(0)
byteStrings.indexOf('c') should ===(2)
byteStrings.indexOf('d') should ===(-1)
@@ -543,7 +543,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
byteStrings.indexOf('f') should ===(4)
byteStrings.indexOf('g') should ===(5)
- val compact = byteStrings.compact
+ val compact: akka.util.CompactByteString = byteStrings.compact
compact.indexOf('a') should ===(0)
compact.indexOf('c') should ===(2)
compact.indexOf('d') should ===(-1)
@@ -556,7 +556,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
ByteString.empty.indexOf(5, -1) should ===(-1)
ByteString.empty.indexOf(5, 0) should ===(-1)
ByteString.empty.indexOf(5, 1) should ===(-1)
- val byteString1 = ByteString1.fromString("abc")
+ val byteString1: akka.util.ByteString.ByteString1 = ByteString1.fromString("abc")
byteString1.indexOf('d', -1) should ===(-1)
byteString1.indexOf('d', 0) should ===(-1)
byteString1.indexOf('d', 1) should ===(-1)
@@ -565,7 +565,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
byteString1.indexOf('a', 0) should ===(0)
byteString1.indexOf('a', 1) should ===(-1)
- val byteStrings = ByteStrings(ByteString1.fromString("abc"), ByteString1.fromString("efg"))
+ val byteStrings: akka.util.ByteString = ByteStrings(ByteString1.fromString("abc"), ByteString1.fromString("efg"))
byteStrings.indexOf('c', -1) should ===(2)
byteStrings.indexOf('c', 0) should ===(2)
byteStrings.indexOf('c', 2) should ===(2)
@@ -584,7 +584,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
byteStrings.indexOf('g', 5) should ===(5)
byteStrings.indexOf('g', 6) should ===(-1)
- val compact = byteStrings.compact
+ val compact: akka.util.CompactByteString = byteStrings.compact
compact.indexOf('c', -1) should ===(2)
compact.indexOf('c', 0) should ===(2)
compact.indexOf('c', 2) should ===(2)
@@ -621,7 +621,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
}
"be equal to the original" when {
- "compacting" in { check { xs: ByteString ⇒ val ys = xs.compact; (xs == ys) && ys.isCompact } }
+ "compacting" in { check { xs: ByteString ⇒ val ys: akka.util.CompactByteString = xs.compact; (xs == ys) && ys.isCompact } }
"recombining" in {
check { (xs: ByteString, from: Int, until: Int) ⇒
val (tmp, c) = xs.splitAt(until)
@@ -629,7 +629,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
(a ++ b ++ c) == xs
}
}
- def excerciseRecombining(xs: ByteString, from: Int, until: Int) = {
+ def excerciseRecombining(xs: ByteString, from: Int, until: Int): org.scalatest.Assertion = {
val (tmp, c) = xs.splitAt(until)
val (a, b) = tmp.splitAt(from)
(a ++ b ++ c) should ===(xs)
@@ -651,8 +651,8 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
"compacting" in {
check { a: ByteString ⇒
- val wasCompact = a.isCompact
- val b = a.compact
+ val wasCompact: Boolean = a.isCompact
+ val b: akka.util.CompactByteString = a.compact
((!wasCompact) || (b eq a)) &&
(b == a) &&
b.isCompact &&
@@ -734,7 +734,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
check { slice: ByteStringSlice ⇒
slice match {
case (xs, from, until) ⇒ likeVector(xs)({ it ⇒
- val array = new Array[Byte](xs.length)
+ val array: Array[Byte] = new Array[Byte](xs.length)
it.slice(from, until).copyToArray(array, from, until)
array.toSeq
})
@@ -746,8 +746,8 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
"serialize correctly" when {
"parsing regular ByteString1C as compat" in {
val oldSerd = "aced000573720021616b6b612e7574696c2e42797465537472696e672442797465537472696e67314336e9eed0afcfe4a40200015b000562797465737400025b427872001b616b6b612e7574696c2e436f6d7061637442797465537472696e67fa2925150f93468f0200007870757200025b42acf317f8060854e002000078700000000a74657374737472696e67"
- val bs = ByteString("teststring", "UTF8")
- val str = hexFromSer(bs)
+ val bs: akka.util.ByteString = ByteString("teststring", "UTF8")
+ val str: String = hexFromSer(bs)
require(oldSerd == str)
}
@@ -760,7 +760,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
"with a large concatenated bytestring" in {
// coverage for #20901
- val original = ByteString(Array.fill[Byte](1000)(1)) ++ ByteString(Array.fill[Byte](1000)(2))
+ val original: akka.util.ByteString = ByteString(Array.fill[Byte](1000)(1)) ++ ByteString(Array.fill[Byte](1000)(2))
deserialize(serialize(original)) shouldEqual original
}
@@ -815,7 +815,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
check { slice: ByteStringSlice ⇒
slice match {
case (xs, from, until) ⇒ likeVecIt(xs)({ it ⇒
- val array = new Array[Byte](xs.length)
+ val array: Array[Byte] = new Array[Byte](xs.length)
it.slice(from, until).copyToArray(array, from, until)
array.toSeq
}, strict = false)
@@ -829,8 +829,8 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
// mixing getByte and getBytes here for more rigorous testing
check { slice: ByteStringSlice ⇒
val (bytes, from, to) = slice
- val input = bytes.iterator
- val output = new Array[Byte](bytes.length)
+ val input: akka.util.ByteIterator = bytes.iterator
+ val output: Array[Byte] = new Array[Byte](bytes.length)
for (i ← 0 until from) output(i) = input.getByte
input.getBytes(output, from, to - from)
for (i ← to until bytes.length) output(i) = input.getByte
@@ -842,7 +842,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
check {
slice: ByteStringSlice ⇒
val (bytes, _, _) = slice
- val input = bytes.iterator
+ val input: akka.util.ByteIterator = bytes.iterator
(input.getBytes(bytes.length).toSeq == bytes) && input.isEmpty
}
}
@@ -851,7 +851,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
check {
slice: ByteStringSlice ⇒
val (bytes, _, _) = slice
- val input = bytes.iterator
+ val input: akka.util.ByteIterator = bytes.iterator
(input.getByteString(bytes.length) == bytes) && input.isEmpty
}
}
@@ -860,17 +860,17 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
// combining skip and both read methods here for more rigorous testing
check { slice: ByteStringSlice ⇒
val (bytes, from, to) = slice
- val a = (0 max from) min bytes.length
- val b = (a max to) min bytes.length
- val input = bytes.iterator
- val output = new Array[Byte](bytes.length)
+ val a: Int = (0 max from) min bytes.length
+ val b: Int = (a max to) min bytes.length
+ val input: akka.util.ByteIterator = bytes.iterator
+ val output: Array[Byte] = new Array[Byte](bytes.length)
input.asInputStream.skip(a)
- val toRead = b - a
+ val toRead: Int = b - a
var (nRead, eof) = (0, false)
while ((nRead < toRead) && !eof) {
- val n = input.asInputStream.read(output, a + nRead, toRead - nRead)
+ val n: Int = input.asInputStream.read(output, a + nRead, toRead - nRead)
if (n == -1) eof = true
else nRead += n
}
@@ -887,10 +887,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
"calling copyToBuffer" in {
check { bytes: ByteString ⇒
import java.nio.ByteBuffer
- val buffer = ByteBuffer.allocate(bytes.size)
+ val buffer: java.nio.ByteBuffer = ByteBuffer.allocate(bytes.size)
bytes.copyToBuffer(buffer)
buffer.flip()
- val array = new Array[Byte](bytes.size)
+ val array: Array[Byte] = new Array[Byte](bytes.size)
buffer.get(array)
bytes == array.toSeq
}
@@ -930,7 +930,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
// mixing putByte and putBytes here for more rigorous testing
check { slice: ArraySlice[Byte] ⇒
val (data, from, to) = slice
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.putByte(data(i))
builder.putBytes(data, from, to - from)
for (i ← to until data.length) builder.putByte(data(i))
@@ -942,7 +942,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
// mixing the write methods here for more rigorous testing
check { slice: ArraySlice[Byte] ⇒
val (data, from, to) = slice
- val builder = ByteString.newBuilder
+ val builder: akka.util.ByteStringBuilder = ByteString.newBuilder
for (i ← 0 until from) builder.asOutputStream.write(data(i).toInt)
builder.asOutputStream.write(data, from, to - from)
for (i ← to until data.length) builder.asOutputStream.write(data(i).toInt)
diff --git a/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala b/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala
index 34bdeb9..3ffb3f3 100644
--- a/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala
@@ -14,10 +14,10 @@ class DurationSpec extends AkkaSpec {
"Duration" must {
"form a one-dimensional vector field" in {
- val zero = 0 seconds
- val one = 1 second
- val two = one + one
- val three = 3 * one
+ val zero: scala.concurrent.duration.FiniteDuration = 0 seconds
+ val one: scala.concurrent.duration.FiniteDuration = 1 second
+ val two: scala.concurrent.duration.FiniteDuration = one + one
+ val three: scala.concurrent.duration.FiniteDuration = 3 * one
(0 * one) should ===(zero)
(2 * one) should ===(two)
(three - two) should ===(one)
@@ -28,10 +28,10 @@ class DurationSpec extends AkkaSpec {
}
"respect correct treatment of infinities" in {
- val one = 1.second
- val inf = Duration.Inf
- val minf = Duration.MinusInf
- val undefined = Duration.Undefined
+ val one: scala.concurrent.duration.FiniteDuration = 1.second
+ val inf: scala.concurrent.duration.Duration.Infinite = Duration.Inf
+ val minf: scala.concurrent.duration.Duration.Infinite = Duration.MinusInf
+ val undefined: scala.concurrent.duration.Duration.Infinite = Duration.Undefined
(-inf) should ===(minf)
(minf + inf) should ===(undefined)
(inf - inf) should ===(undefined)
@@ -83,8 +83,8 @@ class DurationSpec extends AkkaSpec {
}*/
"support fromNow" in {
- val dead = 2.seconds.fromNow
- val dead2 = 2 seconds fromNow
+ val dead: scala.concurrent.duration.Deadline = 2.seconds.fromNow
+ val dead2: scala.concurrent.duration.DurationConversions.fromNowConvert.R = 2 seconds fromNow
// view bounds vs. very local type inference vs. operator precedence: sigh
dead.timeLeft should be > (1 second: Duration)
dead2.timeLeft should be > (1 second: Duration)
diff --git a/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala b/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala
index 298b9f2..21d1088 100644
--- a/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala
@@ -12,44 +12,44 @@ class ImmutableIntMapSpec extends WordSpec with Matchers {
"ImmutableIntMap" must {
"have no entries when empty" in {
- val empty = ImmutableIntMap.empty
+ val empty: akka.util.ImmutableIntMap = ImmutableIntMap.empty
empty.size should be(0)
empty.keysIterator.toList should be(Nil)
}
"add and get entries" in {
- val m1 = ImmutableIntMap.empty.updated(10, 10)
+ val m1: akka.util.ImmutableIntMap = ImmutableIntMap.empty.updated(10, 10)
m1.keysIterator.toList should be(List(10))
m1.keysIterator.map(m1.get).toList should be(List(10))
- val m2 = m1.updated(20, 20)
+ val m2: akka.util.ImmutableIntMap = m1.updated(20, 20)
m2.keysIterator.toList should be(List(10, 20))
m2.keysIterator.map(m2.get).toList should be(List(10, 20))
- val m3 = m1.updated(5, 5)
+ val m3: akka.util.ImmutableIntMap = m1.updated(5, 5)
m3.keysIterator.toList should be(List(5, 10))
m3.keysIterator.map(m3.get).toList should be(List(5, 10))
- val m4 = m2.updated(5, 5)
+ val m4: akka.util.ImmutableIntMap = m2.updated(5, 5)
m4.keysIterator.toList should be(List(5, 10, 20))
m4.keysIterator.map(m4.get).toList should be(List(5, 10, 20))
- val m5 = m4.updated(15, 15)
+ val m5: akka.util.ImmutableIntMap = m4.updated(15, 15)
m5.keysIterator.toList should be(List(5, 10, 15, 20))
m5.keysIterator.map(m5.get).toList should be(List(5, 10, 15, 20))
}
"replace entries" in {
- val m1 = ImmutableIntMap.empty.updated(10, 10).updated(10, 11)
+ val m1: akka.util.ImmutableIntMap = ImmutableIntMap.empty.updated(10, 10).updated(10, 11)
m1.keysIterator.map(m1.get).toList should be(List(11))
- val m2 = m1.updated(20, 20).updated(30, 30)
+ val m2: akka.util.ImmutableIntMap = m1.updated(20, 20).updated(30, 30)
.updated(20, 21).updated(30, 31)
m2.keysIterator.map(m2.get).toList should be(List(11, 21, 31))
}
"update if absent" in {
- val m1 = ImmutableIntMap.empty.updated(10, 10).updated(20, 11)
+ val m1: akka.util.ImmutableIntMap = ImmutableIntMap.empty.updated(10, 10).updated(20, 11)
m1.updateIfAbsent(10, 15) should be(ImmutableIntMap.empty.updated(10, 10).updated(20, 11))
m1.updateIfAbsent(30, 12) should be(ImmutableIntMap.empty.updated(10, 10).updated(20, 11).updated(30, 12))
}
@@ -84,15 +84,15 @@ class ImmutableIntMapSpec extends WordSpec with Matchers {
}
"remove entries" in {
- val m1 = ImmutableIntMap.empty.updated(10, 10).updated(20, 20).updated(30, 30)
+ val m1: akka.util.ImmutableIntMap = ImmutableIntMap.empty.updated(10, 10).updated(20, 20).updated(30, 30)
- val m2 = m1.remove(10)
+ val m2: akka.util.ImmutableIntMap = m1.remove(10)
m2.keysIterator.map(m2.get).toList should be(List(20, 30))
- val m3 = m1.remove(20)
+ val m3: akka.util.ImmutableIntMap = m1.remove(20)
m3.keysIterator.map(m3.get).toList should be(List(10, 30))
- val m4 = m1.remove(30)
+ val m4: akka.util.ImmutableIntMap = m1.remove(30)
m4.keysIterator.map(m4.get).toList should be(List(10, 20))
m1.remove(5) should be(m1)
@@ -101,7 +101,7 @@ class ImmutableIntMapSpec extends WordSpec with Matchers {
}
"get None when entry doesn't exist" in {
- val m1 = ImmutableIntMap.empty.updated(10, 10).updated(20, 20).updated(30, 30)
+ val m1: akka.util.ImmutableIntMap = ImmutableIntMap.empty.updated(10, 10).updated(20, 20).updated(30, 30)
m1.get(5) should be(Int.MinValue)
m1.get(15) should be(Int.MinValue)
m1.get(25) should be(Int.MinValue)
@@ -109,7 +109,7 @@ class ImmutableIntMapSpec extends WordSpec with Matchers {
}
"contain keys" in {
- val m1 = ImmutableIntMap.empty.updated(10, 10).updated(20, 20).updated(30, 30)
+ val m1: akka.util.ImmutableIntMap = ImmutableIntMap.empty.updated(10, 10).updated(20, 20).updated(30, 30)
m1.contains(10) should be(true)
m1.contains(20) should be(true)
m1.contains(30) should be(true)
@@ -118,22 +118,22 @@ class ImmutableIntMapSpec extends WordSpec with Matchers {
}
"have correct behavior for random operations" in {
- val seed = System.nanoTime()
- val rnd = new Random(seed)
+ val seed: Long = System.nanoTime()
+ val rnd: scala.util.Random = new Random(seed)
var longMap = ImmutableIntMap.empty
var reference = Map.empty[Long, Int]
def verify(): Unit = {
- val m = longMap.keysIterator.map(key ⇒ key → longMap.get(key)).toMap
+ val m: scala.collection.immutable.Map[Int, Int] = longMap.keysIterator.map(key ⇒ key → longMap.get(key)).toMap
m should be(reference)
}
(1 to 1000).foreach { i ⇒
withClue(s"seed=$seed, iteration=$i") {
- val key = rnd.nextInt(100)
- val value = rnd.nextPrintableChar()
+ val key: Int = rnd.nextInt(100)
+ val value: Char = rnd.nextPrintableChar()
rnd.nextInt(3) match {
case 0 | 1 ⇒
longMap = longMap.updated(key, value)
diff --git a/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala b/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala
index 7d8bc0f..e73ec30 100644
--- a/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala
@@ -12,13 +12,13 @@ import scala.util.Random
import akka.testkit.DefaultTimeout
class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
- implicit val ec = system.dispatcher
+ implicit val ec: scala.concurrent.ExecutionContextExecutor = system.dispatcher
private def emptyIndex = new Index[String, Int](100, new Comparator[Int] {
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
})
private def indexWithValues = {
- val index = emptyIndex
+ val index: akka.util.Index[String, Int] = emptyIndex
index.put("s1", 1)
index.put("s1", 2)
index.put("s1", 3)
@@ -32,12 +32,12 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
"An Index" must {
"take and return a value" in {
- val index = emptyIndex
+ val index: akka.util.Index[String, Int] = emptyIndex
index.put("s1", 1)
index.valueIterator("s1").toSet should be(Set(1))
}
"take and return several values" in {
- val index = emptyIndex
+ val index: akka.util.Index[String, Int] = emptyIndex
index.put("s1", 1) should ===(true)
index.put("s1", 1) should ===(false)
index.put("s1", 2)
@@ -47,7 +47,7 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
index.valueIterator("s2").toSet should ===(Set(4))
}
"remove values" in {
- val index = emptyIndex
+ val index: akka.util.Index[String, Int] = emptyIndex
index.put("s1", 1)
index.put("s1", 2)
index.put("s2", 1)
@@ -65,7 +65,7 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
index.valueIterator("s2").toSet should ===(Set.empty[Int])
}
"remove the specified value" in {
- val index = emptyIndex
+ val index: akka.util.Index[String, Int] = emptyIndex
index.put("s1", 1)
index.put("s1", 2)
index.put("s1", 3)
@@ -79,7 +79,7 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
index.valueIterator("s3").toSet should ===(Set(2))
}
"apply a function for all key-value pairs and find every value" in {
- val index = indexWithValues
+ val index: akka.util.Index[String, Int] = indexWithValues
var valueCount = 0
index.foreach((key, value) ⇒ {
@@ -89,13 +89,13 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
valueCount should ===(6)
}
"be cleared" in {
- val index = indexWithValues
+ val index: akka.util.Index[String, Int] = indexWithValues
index.isEmpty should ===(false)
index.clear()
index.isEmpty should ===(true)
}
"be able to be accessed in parallel" in {
- val index = new Index[Int, Int](100, new Comparator[Int] {
+ val index: akka.util.Index[Int, Int] = new Index[Int, Int](100, new Comparator[Int] {
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
})
val nrOfTasks = 10000
@@ -105,31 +105,31 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
for (key ← 0 until nrOfKeys; value ← 0 until nrOfValues)
index.put(key, value)
//Tasks to be executed in parallel
- def putTask() = Future {
+ def putTask(): scala.concurrent.Future[Boolean] = Future {
index.put(Random.nextInt(nrOfKeys), Random.nextInt(nrOfValues))
}
- def removeTask1() = Future {
+ def removeTask1(): scala.concurrent.Future[Boolean] = Future {
index.remove(Random.nextInt(nrOfKeys / 2), Random.nextInt(nrOfValues))
}
- def removeTask2() = Future {
+ def removeTask2(): scala.concurrent.Future[Option[Iterable[Int]]] = Future {
index.remove(Random.nextInt(nrOfKeys / 2))
}
- def readTask() = Future {
- val key = Random.nextInt(nrOfKeys)
- val values = index.valueIterator(key)
+ def readTask(): scala.concurrent.Future[Any] = Future {
+ val key: Int = Random.nextInt(nrOfKeys)
+ val values: Iterator[Int] = index.valueIterator(key)
if (key >= nrOfKeys / 2) {
values.isEmpty should ===(false)
}
}
- def executeRandomTask() = Random.nextInt(4) match {
+ def executeRandomTask(): scala.concurrent.Future[Any] = Random.nextInt(4) match {
case 0 ⇒ putTask()
case 1 ⇒ removeTask1()
case 2 ⇒ removeTask2()
case 3 ⇒ readTask()
}
- val tasks = List.fill(nrOfTasks)(executeRandomTask)
+ val tasks: List[scala.concurrent.Future[Any]] = List.fill(nrOfTasks)(executeRandomTask)
tasks.foreach(Await.result(_, timeout.duration))
}
diff --git a/akka-actor-tests/src/test/scala/akka/util/LineNumberSpec.scala b/akka-actor-tests/src/test/scala/akka/util/LineNumberSpec.scala
index 9c51098..d9aeeb3 100644
--- a/akka-actor-tests/src/test/scala/akka/util/LineNumberSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/LineNumberSpec.scala
@@ -18,7 +18,7 @@ class LineNumberSpec extends AkkaSpec {
import LineNumberSpecCodeForScala._
"work for small functions" in {
- val result = LineNumbers(oneline)
+ val result: akka.util.LineNumbers.Result = LineNumbers(oneline)
if (isScala212)
// because how scala 2.12 does the same as Java Lambdas
@@ -28,7 +28,7 @@ class LineNumberSpec extends AkkaSpec {
}
"work for larger functions" in {
- val result = LineNumbers(twoline)
+ val result: akka.util.LineNumbers.Result = LineNumbers(twoline)
if (isScala212)
// because how scala 2.12 does the same as Java Lambdas
result should ===(NoSourceInfo)
@@ -43,7 +43,7 @@ class LineNumberSpec extends AkkaSpec {
}
"writing Java" must {
- val l = new LineNumberSpecCodeForJava
+ val l: akka.util.LineNumberSpecCodeForJava = new LineNumberSpecCodeForJava
"work for small functions" in {
// because how java Lambdas are implemented/designed
diff --git a/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala b/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala
index 3ce3267..7c6dad4 100644
--- a/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala
@@ -9,9 +9,9 @@ package akka.util
object LineNumberSpecCodeForScala {
- val oneline = (s: String) ⇒ println(s)
+ val oneline: String ⇒ Unit = (s: String) ⇒ println(s)
- val twoline = (s: String) ⇒ {
+ val twoline: String ⇒ Int = (s: String) ⇒ {
println(s)
Integer.parseInt(s)
}
diff --git a/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala b/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala
index 0649923..cf10f76 100644
--- a/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala
@@ -15,7 +15,7 @@ class MessageBufferSpec extends WordSpec with Matchers {
"A MessageBuffer" must {
"answer empty correctly" in {
- val buffer = MessageBuffer.empty
+ val buffer: akka.util.MessageBuffer = MessageBuffer.empty
buffer.isEmpty should ===(true)
buffer.nonEmpty should ===(false)
buffer.append("m1", "s1")
@@ -24,7 +24,7 @@ class MessageBufferSpec extends WordSpec with Matchers {
}
"append and drop" in {
- val buffer = MessageBuffer.empty
+ val buffer: akka.util.MessageBuffer = MessageBuffer.empty
buffer.size should ===(0)
buffer.append("m1", "s1")
buffer.size should ===(1)
@@ -46,15 +46,15 @@ class MessageBufferSpec extends WordSpec with Matchers {
}
"process elements in the right order" in {
- val buffer = MessageBuffer.empty
+ val buffer: akka.util.MessageBuffer = MessageBuffer.empty
buffer.append("m1", "s1")
buffer.append("m2", "s2")
buffer.append("m3", "s3")
- val sb1 = new StringBuilder()
+ val sb1: StringBuilder = new StringBuilder()
buffer.foreach((m, s) ⇒ sb1.append(s"$m->$s:"))
sb1.toString() should ===("m1->s1:m2->s2:m3->s3:")
buffer.dropHead()
- val sb2 = new StringBuilder()
+ val sb2: StringBuilder = new StringBuilder()
buffer.foreach((m, s) ⇒ sb2.append(s"$m->$s:"))
sb2.toString() should ===("m2->s2:m3->s3:")
}
@@ -63,7 +63,7 @@ class MessageBufferSpec extends WordSpec with Matchers {
"A MessageBufferMap" must {
"support contains, add, append and remove" in {
- val map = new MessageBufferMap[String]
+ val map: akka.util.MessageBufferMap[String] = new MessageBufferMap[String]
map.contains("id1") should ===(false)
map.getOrEmpty("id1").isEmpty should ===(true)
map.totalSize should ===(0)
@@ -82,13 +82,13 @@ class MessageBufferSpec extends WordSpec with Matchers {
}
"handle multiple message buffers" in {
- val map = new MessageBufferMap[String]
+ val map: akka.util.MessageBufferMap[String] = new MessageBufferMap[String]
map.append("id1", "m11", "s11")
map.append("id1", "m12", "s12")
map.append("id2", "m21", "s21")
map.append("id2", "m22", "s22")
map.totalSize should ===(4)
- val sb = new StringBuilder()
+ val sb: StringBuilder = new StringBuilder()
map.getOrEmpty("id1").foreach((m, s) ⇒ sb.append(s"id1->$m->$s:"))
map.getOrEmpty("id2").foreach((m, s) ⇒ sb.append(s"id2->$m->$s:"))
sb.toString() should ===("id1->m11->s11:id1->m12->s12:id2->m21->s21:id2->m22->s22:")
diff --git a/akka-actor-tests/src/test/scala/akka/util/ReflectSpec.scala b/akka-actor-tests/src/test/scala/akka/util/ReflectSpec.scala
index fde4f41..ab8849d 100644
--- a/akka-actor-tests/src/test/scala/akka/util/ReflectSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/ReflectSpec.scala
@@ -37,7 +37,7 @@ class ReflectSpec extends WordSpec with Matchers {
Reflect.findConstructor(classOf[Two], immutable.Seq(null, new B))
}
"deal with `null` in 1 matching case" in {
- val constructor = Reflect.findConstructor(classOf[One], immutable.Seq(null))
+ val constructor: java.lang.reflect.Constructor[akka.util.ReflectSpec.One] = Reflect.findConstructor(classOf[One], immutable.Seq(null))
constructor.newInstance(null)
}
"deal with multiple constructors" in {
diff --git a/akka-actor-tests/src/test/scala/akka/util/SwitchSpec.scala b/akka-actor-tests/src/test/scala/akka/util/SwitchSpec.scala
index d595167..3848311 100644
--- a/akka-actor-tests/src/test/scala/akka/util/SwitchSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/SwitchSpec.scala
@@ -13,7 +13,7 @@ class SwitchSpec extends WordSpec with Matchers {
"Switch" must {
"on and off" in {
- val s = new Switch(false)
+ val s: akka.util.Switch = new Switch(false)
s.isOff should ===(true)
s.isOn should ===(false)
@@ -33,7 +33,7 @@ class SwitchSpec extends WordSpec with Matchers {
}
"revert when exception" in {
- val s = new Switch(false)
+ val s: akka.util.Switch = new Switch(false)
intercept[RuntimeException] {
s.switchOn(throw new RuntimeException)
}
@@ -41,7 +41,7 @@ class SwitchSpec extends WordSpec with Matchers {
}
"run action without locking" in {
- val s = new Switch(false)
+ val s: akka.util.Switch = new Switch(false)
s.ifOffYield("yes") should ===(Some("yes"))
s.ifOnYield("no") should ===(None)
s.ifOff(()) should ===(true)
@@ -55,7 +55,7 @@ class SwitchSpec extends WordSpec with Matchers {
}
"run action with locking" in {
- val s = new Switch(false)
+ val s: akka.util.Switch = new Switch(false)
s.whileOffYield("yes") should ===(Some("yes"))
s.whileOnYield("no") should ===(None)
s.whileOff(()) should ===(true)
@@ -69,14 +69,14 @@ class SwitchSpec extends WordSpec with Matchers {
}
"run first or second action depending on state" in {
- val s = new Switch(false)
+ val s: akka.util.Switch = new Switch(false)
s.fold("on")("off") should ===("off")
s.switchOn(())
s.fold("on")("off") should ===("on")
}
"do proper locking" in {
- val s = new Switch(false)
+ val s: akka.util.Switch = new Switch(false)
s.locked {
Thread.sleep(500)
@@ -84,7 +84,7 @@ class SwitchSpec extends WordSpec with Matchers {
s.isOn should ===(true)
}
- val latch = new CountDownLatch(1)
+ val latch: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
new Thread {
override def run(): Unit = {
s.switchOff(())
diff --git a/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala b/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala
index 18f60c4..a9606e3 100644
--- a/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala
@@ -16,7 +16,7 @@ class TokenBucketSpec extends AkkaSpec {
"A Token Bucket" must {
"start full" in {
- val bucket = new TestBucket(10, 1)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, 1)
bucket.init()
bucket.offer(1) should ===(0)
@@ -28,14 +28,14 @@ class TokenBucketSpec extends AkkaSpec {
}
"calculate correctly with different rates and capacities" in {
- val bucketRate2 = new TestBucket(10, 2)
+ val bucketRate2: TokenBucketSpec.this.TestBucket = new TestBucket(10, 2)
bucketRate2.init()
bucketRate2.offer(5) should ===(0)
bucketRate2.offer(5) should ===(0)
bucketRate2.offer(5) should ===(10)
- val bucketRate3 = new TestBucket(8, 3)
+ val bucketRate3: TokenBucketSpec.this.TestBucket = new TestBucket(8, 3)
bucketRate3.init()
bucketRate3.offer(5) should ===(0)
bucketRate3.offer(5) should ===(6)
@@ -45,7 +45,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"allow sending elements larger than capacity" in {
- val bucket = new TestBucket(10, 2)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, 2)
bucket.init()
bucket.offer(5) should ===(0)
@@ -60,7 +60,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"work with zero capacity" in {
- val bucket = new TestBucket(0, 2)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(0, 2)
bucket.init()
bucket.offer(10) should ===(20)
@@ -70,7 +70,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"not delay if rate is higher than production" in {
- val bucket = new TestBucket(1, 10)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(1, 10)
bucket.init()
for (time ← 0 to 100 by 10) {
@@ -81,7 +81,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"maintain maximum capacity" in {
- val bucket = new TestBucket(10, 1)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, 1)
bucket.init()
bucket.offer(10) should ===(0)
@@ -90,7 +90,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"work if currentTime is negative" in {
- val bucket = new TestBucket(10, 1)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, 1)
bucket.currentTime = -100 // Must be set before init()!
bucket.init()
@@ -103,7 +103,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"work if currentTime wraps over" in {
- val bucket = new TestBucket(10, 1)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, 1)
bucket.currentTime = Long.MaxValue - 5 // Must be set before init()!
bucket.init()
@@ -116,7 +116,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"(attempt to) maintain equal time between token renewal intervals" in {
- val bucket = new TestBucket(5, 3)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(5, 3)
bucket.init()
bucket.offer(10) should ===(15)
@@ -145,7 +145,7 @@ class TokenBucketSpec extends AkkaSpec {
bucket.offer(2) should ===(5)
// Another case
- val bucket2 = new TestBucket(10, 3)
+ val bucket2: TokenBucketSpec.this.TestBucket = new TestBucket(10, 3)
bucket2.init()
bucket2.currentTime = 4
@@ -158,7 +158,7 @@ class TokenBucketSpec extends AkkaSpec {
}
"work with cost of zero" in {
- val bucket = new TestBucket(10, 1)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, 1)
bucket.init()
// Can be called any number of times
@@ -176,8 +176,8 @@ class TokenBucketSpec extends AkkaSpec {
}
"work with very slow rates" in {
- val T = Long.MaxValue >> 10
- val bucket = new TestBucket(10, T)
+ val T: Long = Long.MaxValue >> 10
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(10, T)
bucket.init()
bucket.offer(20) should ===(10 * T)
@@ -201,7 +201,7 @@ class TokenBucketSpec extends AkkaSpec {
maxCost ← List(1, 5, 10)
} {
- val bucket = new TestBucket(capacity, period)
+ val bucket: TokenBucketSpec.this.TestBucket = new TestBucket(capacity, period)
bucket.currentTime = startTime
bucket.init()
@@ -229,10 +229,10 @@ class TokenBucketSpec extends AkkaSpec {
if (untilNextElement == 0) {
// Allow cost of zer
- val cost = Random.nextInt(maxCost + 1)
+ val cost: Int = Random.nextInt(maxCost + 1)
idealBucket -= cost // This can go negative
bucket.currentTime = startTime + time
- val delay = bucket.offer(cost)
+ val delay: Long = bucket.offer(cost)
nextEmit = time + delay
if (Debug) println(s" ARRIVAL cost: $cost at: $nextEmit")
if (delay == 0) {
diff --git a/akka-actor-tests/src/test/scala/akka/util/TypedMultiMapSpec.scala b/akka-actor-tests/src/test/scala/akka/util/TypedMultiMapSpec.scala
index 7333072..084af4f 100644
--- a/akka-actor-tests/src/test/scala/akka/util/TypedMultiMapSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/TypedMultiMapSpec.scala
@@ -21,7 +21,7 @@ class TypedMultiMapSpec extends WordSpec with Matchers with ConversionCheckedTri
"A TypedMultiMap" must {
"retain and remove values for the same key" in {
- val m1 = TypedMultiMap.empty[AbstractKey, KV]
+ val m1: akka.util.TypedMultiMap[akka.util.TypedMultiMapSpec.AbstractKey, akka.util.TypedMultiMapSpec.KV] = TypedMultiMap.empty[AbstractKey, KV]
val m2 = m1.inserted(Key(1))(MyValue(42))
m2.get(Key(1)) should ===(Set(MyValue(42)))
m2.removed(Key(1))(MyValue(42)).get(Key(1)) should ===(Set.empty[MyValue[Int]])
@@ -31,7 +31,7 @@ class TypedMultiMapSpec extends WordSpec with Matchers with ConversionCheckedTri
}
"retain and remove values for multiple keys" in {
- val m1 = TypedMultiMap.empty[AbstractKey, KV]
+ val m1: akka.util.TypedMultiMap[akka.util.TypedMultiMapSpec.AbstractKey, akka.util.TypedMultiMapSpec.KV] = TypedMultiMap.empty[AbstractKey, KV]
val m2 = m1.inserted(Key(1))(MyValue(42)).inserted(Key(2))(MyValue(43))
m2.get(Key(1)) should ===(Set(MyValue(42)))
m2.removed(Key(1))(MyValue(42)).get(Key(1)) should ===(Set.empty[MyValue[Int]])
@@ -40,7 +40,7 @@ class TypedMultiMapSpec extends WordSpec with Matchers with ConversionCheckedTri
}
"remove a value from all keys" in {
- val m1 = TypedMultiMap.empty[AbstractKey, KV]
+ val m1: akka.util.TypedMultiMap[akka.util.TypedMultiMapSpec.AbstractKey, akka.util.TypedMultiMapSpec.KV] = TypedMultiMap.empty[AbstractKey, KV]
val m2 = m1.inserted(Key(1))(MyValue(42)).inserted(Key(2))(MyValue(43)).inserted(Key(2))(MyValue(42))
val m3 = m2.valueRemoved(MyValue(42))
m3.get(Key(1)) should ===(Set.empty[MyValue[Int]])
@@ -49,7 +49,7 @@ class TypedMultiMapSpec extends WordSpec with Matchers with ConversionCheckedTri
}
"remove all values from a key" in {
- val m1 = TypedMultiMap.empty[AbstractKey, KV]
+ val m1: akka.util.TypedMultiMap[akka.util.TypedMultiMapSpec.AbstractKey, akka.util.TypedMultiMapSpec.KV] = TypedMultiMap.empty[AbstractKey, KV]
val m2 = m1.inserted(Key(1))(MyValue(42)).inserted(Key(2))(MyValue(43)).inserted(Key(2))(MyValue(42))
val m3 = m2.keyRemoved(Key(1))
m3.get(Key(1)) should ===(Set.empty[MyValue[Int]])
@@ -58,12 +58,12 @@ class TypedMultiMapSpec extends WordSpec with Matchers with ConversionCheckedTri
}
"reject invalid insertions" in {
- val m1 = TypedMultiMap.empty[AbstractKey, KV]
+ val m1: akka.util.TypedMultiMap[akka.util.TypedMultiMapSpec.AbstractKey, akka.util.TypedMultiMapSpec.KV] = TypedMultiMap.empty[AbstractKey, KV]
"m1.inserted(Key(1))(MyValue(42L))" shouldNot compile
}
"reject invalid removals" in {
- val m1 = TypedMultiMap.empty[AbstractKey, KV]
+ val m1: akka.util.TypedMultiMap[akka.util.TypedMultiMapSpec.AbstractKey, akka.util.TypedMultiMapSpec.KV] = TypedMultiMap.empty[AbstractKey, KV]
"m1.removed(Key(1))(MyValue(42L))" shouldNot compile
}
diff --git a/akka-actor-tests/src/test/scala/akka/util/WildcardIndexSpec.scala b/akka-actor-tests/src/test/scala/akka/util/WildcardIndexSpec.scala
index 0f35ce9..f2bf931 100644
--- a/akka-actor-tests/src/test/scala/akka/util/WildcardIndexSpec.scala
+++ b/akka-actor-tests/src/test/scala/akka/util/WildcardIndexSpec.scala
@@ -16,7 +16,7 @@ class WildcardIndexSpec extends WordSpec with Matchers {
}
"allow to find inserted elements" in {
- val tree = emptyIndex.insert(Array("a"), 1).insert(Array("a", "b"), 2).insert(Array("a", "c"), 3)
+ val tree: akka.util.WildcardIndex[Int] = emptyIndex.insert(Array("a"), 1).insert(Array("a", "b"), 2).insert(Array("a", "c"), 3)
tree.find(Array("a", "b")).get shouldBe 2
tree.find(Array("a")).get shouldBe 1
tree.find(Array("x")) shouldBe None
@@ -24,13 +24,13 @@ class WildcardIndexSpec extends WordSpec with Matchers {
}
"match all elements in the subArray when it contains a wildcard" in {
- val tree1 = emptyIndex.insert(Array("a"), 1).insert(Array("a", "*"), 1)
+ val tree1: akka.util.WildcardIndex[Int] = emptyIndex.insert(Array("a"), 1).insert(Array("a", "*"), 1)
tree1.find(Array("z")) shouldBe None
tree1.find(Array("a")).get shouldBe 1
tree1.find(Array("a", "b")).get shouldBe 1
tree1.find(Array("a", "x")).get shouldBe 1
- val tree2 = emptyIndex.insert(Array("a", "*"), 1).insert(Array("a", "*", "c"), 2)
+ val tree2: akka.util.WildcardIndex[Int] = emptyIndex.insert(Array("a", "*"), 1).insert(Array("a", "*", "c"), 2)
tree2.find(Array("z")) shouldBe None
tree2.find(Array("a", "b")).get shouldBe 1
tree2.find(Array("a", "x")).get shouldBe 1
@@ -45,19 +45,19 @@ class WildcardIndexSpec extends WordSpec with Matchers {
}
"match all remaining elements when it contains a terminal double wildcard" in {
- val tree1 = emptyIndex.insert(Array("a", "**"), 1)
+ val tree1: akka.util.WildcardIndex[Int] = emptyIndex.insert(Array("a", "**"), 1)
tree1.find(Array("z")) shouldBe None
tree1.find(Array("a", "b")).get shouldBe 1
tree1.find(Array("a", "x")).get shouldBe 1
tree1.find(Array("a", "x", "y")).get shouldBe 1
- val tree2 = emptyIndex.insert(Array("**"), 1)
+ val tree2: akka.util.WildcardIndex[Int] = emptyIndex.insert(Array("**"), 1)
tree2.find(Array("anything", "I", "want")).get shouldBe 1
tree2.find(Array("anything")).get shouldBe 1
}
"ignore non-terminal double wildcards" in {
- val tree = emptyIndex.insert(Array("a", "**", "c"), 1)
+ val tree: akka.util.WildcardIndex[Int] = emptyIndex.insert(Array("a", "**", "c"), 1)
tree.find(Array("a", "x", "y", "c")) shouldBe None
tree.find(Array("a", "x", "y")) shouldBe None
}
diff --git a/akka-actor/src/main/scala/akka/Main.scala b/akka-actor/src/main/scala/akka/Main.scala
index 4bdc749..083ba3eb 100644
--- a/akka-actor/src/main/scala/akka/Main.scala
+++ b/akka-actor/src/main/scala/akka/Main.scala
@@ -27,11 +27,11 @@ object Main {
if (args.length != 1) {
println("you need to provide exactly one argument: the class of the application supervisor actor")
} else {
- val system = ActorSystem("Main")
+ val system: akka.actor.ActorSystem = ActorSystem("Main")
try {
- val appClass = system.asInstanceOf[ExtendedActorSystem].dynamicAccess.getClassFor[Actor](args(0)).get
- val app = system.actorOf(Props(appClass), "app")
- val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
+ val appClass: Class[_ <: akka.actor.Actor] = system.asInstanceOf[ExtendedActorSystem].dynamicAccess.getClassFor[Actor](args(0)).get
+ val app: akka.actor.ActorRef = system.actorOf(Props(appClass), "app")
+ val terminator: akka.actor.ActorRef = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
} catch {
case NonFatal(e) ⇒ system.terminate(); throw e
}
@@ -40,7 +40,7 @@ object Main {
class Terminator(app: ActorRef) extends Actor with ActorLogging {
context watch app
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Terminated(_) ⇒
log.info("application supervisor has terminated, shutting down")
context.system.terminate()
diff --git a/akka-actor/src/main/scala/akka/actor/AbstractProps.scala b/akka-actor/src/main/scala/akka/actor/AbstractProps.scala
index 5fe9614..f6ee27f 100644
--- a/akka-actor/src/main/scala/akka/actor/AbstractProps.scala
+++ b/akka-actor/src/main/scala/akka/actor/AbstractProps.scala
@@ -40,12 +40,12 @@ private[akka] trait AbstractProps {
* Use the Props.create(actorClass, creator) instead.
*/
def create[T <: Actor](creator: Creator[T]): Props = {
- val cc = creator.getClass
+ val cc: Class[_ <: akka.japi.Creator[T]] = creator.getClass
checkCreatorClosingOver(cc)
- val ac = classOf[Actor]
- val coc = classOf[Creator[_]]
- val actorClass = Reflect.findMarker(cc, coc) match {
+ val ac: Class[akka.actor.Actor] = classOf[Actor]
+ val coc: Class[akka.japi.Creator[_]] = classOf[Creator[_]]
+ val actorClass: Class[_] = Reflect.findMarker(cc, coc) match {
case t: ParameterizedType ⇒
t.getActualTypeArguments.head match {
case c: Class[_] ⇒ c // since T <: Actor
@@ -67,7 +67,7 @@ private[akka] trait AbstractProps {
}
private def checkCreatorClosingOver(clazz: Class[_]): Unit = {
- val enclosingClass = clazz.getEnclosingClass
+ val enclosingClass: Class[_] = clazz.getEnclosingClass
def hasDeclaredConstructorWithEmptyParams(declaredConstructors: Array[Constructor[_]]): Boolean = {
@tailrec def loop(i: Int): Boolean = {
@@ -86,7 +86,7 @@ private[akka] trait AbstractProps {
@tailrec def loop(i: Int): Boolean = {
if (i == declaredConstructors.length) false
else {
- val c = declaredConstructors(i)
+ val c: java.lang.reflect.Constructor[_] = declaredConstructors(i)
if (c.getParameterCount >= 1 && c.getParameterTypes()(0) == enclosingClass)
true
else
@@ -97,11 +97,11 @@ private[akka] trait AbstractProps {
}
def hasValidConstructor: Boolean = {
- val constructorsLength = clazz.getConstructors.length
+ val constructorsLength: Int = clazz.getConstructors.length
if (constructorsLength > 0)
true
else {
- val decl = clazz.getDeclaredConstructors
+ val decl: Array[java.lang.reflect.Constructor[_]] = clazz.getDeclaredConstructors
// the hasDeclaredConstructorWithEnclosingClassParam check is for supporting `new Creator<SomeActor> {`
// which was supported in versions before 2.4.5
hasDeclaredConstructorWithEmptyParams(decl) || !hasDeclaredConstructorWithEnclosingClassParam(decl)
diff --git a/akka-actor/src/main/scala/akka/actor/Actor.scala b/akka-actor/src/main/scala/akka/actor/Actor.scala
index fab26a2..269a6ab 100644
--- a/akka-actor/src/main/scala/akka/actor/Actor.scala
+++ b/akka-actor/src/main/scala/akka/actor/Actor.scala
@@ -40,7 +40,7 @@ case object PoisonPill extends PoisonPill {
/**
* Java API: get the singleton instance
*/
- def getInstance = this
+ def getInstance: akka.actor.PoisonPill.type = this
}
abstract class Kill extends AutoReceivedMessage with PossiblyHarmful
@@ -53,7 +53,7 @@ case object Kill extends Kill {
/**
* Java API: get the singleton instance
*/
- def getInstance = this
+ def getInstance: akka.actor.Kill.type = this
}
/**
@@ -140,7 +140,7 @@ case object ReceiveTimeout extends ReceiveTimeout {
/**
* Java API: get the singleton instance
*/
- def getInstance = this
+ def getInstance: akka.actor.ReceiveTimeout.type = this
}
/**
@@ -339,7 +339,7 @@ trait ActorLogging { this: Actor ⇒
*/
trait DiagnosticActorLogging extends Actor {
import akka.event.Logging._
- val log = akka.event.Logging(this)
+ val log: akka.event.DiagnosticLoggingAdapter = akka.event.Logging(this)
def mdc(currentMessage: Any): MDC = emptyMDC
override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = try {
@@ -365,7 +365,7 @@ object Actor {
@SerialVersionUID(1L)
object emptyBehavior extends Receive {
def isDefinedAt(x: Any) = false
- def apply(x: Any) = throw new UnsupportedOperationException("Empty behavior apply()")
+ def apply(x: Any): Nothing = throw new UnsupportedOperationException("Empty behavior apply()")
}
/**
@@ -463,12 +463,12 @@ trait Actor {
* context.
*/
implicit val context: ActorContext = {
- val contextStack = ActorCell.contextStack.get
+ val contextStack: List[akka.actor.ActorContext] = ActorCell.contextStack.get
if ((contextStack.isEmpty) || (contextStack.head eq null))
throw ActorInitializationException(
s"You cannot create an instance of [${getClass.getName}] explicitly using the constructor (new). " +
"You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.")
- val c = contextStack.head
+ val c: akka.actor.ActorContext = contextStack.head
ActorCell.contextStack.set(null :: contextStack)
c
}
@@ -481,7 +481,7 @@ trait Actor {
* self ! message
* </pre>
*/
- implicit final val self = context.self //MUST BE A VAL, TRUST ME
+ implicit final val self: akka.actor.ActorRef = context.self //MUST BE A VAL, TRUST ME
/**
* The reference sender Actor of the last received message.
diff --git a/akka-actor/src/main/scala/akka/actor/ActorCell.scala b/akka-actor/src/main/scala/akka/actor/ActorCell.scala
index 7dbcf41..99b21d9 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorCell.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorCell.scala
@@ -323,7 +323,7 @@ private[akka] trait Cell {
* for! (waves hand)
*/
private[akka] object ActorCell {
- val contextStack = new ThreadLocal[List[ActorContext]] {
+ val contextStack: ThreadLocal[List[akka.actor.ActorContext]] = new ThreadLocal[List[ActorContext]] {
override def initialValue: List[ActorContext] = Nil
}
@@ -343,13 +343,13 @@ private[akka] object ActorCell {
@tailrec final def newUid(): Int = {
// Note that this uid is also used as hashCode in ActorRef, so be careful
// to not break hashing if you change the way uid is generated
- val uid = ThreadLocalRandom.current.nextInt()
+ val uid: Int = ThreadLocalRandom.current.nextInt()
if (uid == undefinedUid) newUid
else uid
}
final def splitNameAndUid(name: String): (String, Int) = {
- val i = name.indexOf('#')
+ val i: Int = name.indexOf('#')
if (i < 0) (name, undefinedUid)
else (name.substring(0, i), Integer.valueOf(name.substring(i + 1)))
}
@@ -384,10 +384,10 @@ private[akka] class ActorCell(
final def isLocal = true
- final def systemImpl = system
- protected final def guardian = self
- protected final def lookupRoot = self
- final def provider = system.provider
+ final def systemImpl: akka.actor.ActorSystemImpl = system
+ protected final def guardian: akka.actor.InternalActorRef = self
+ protected final def lookupRoot: akka.actor.InternalActorRef = self
+ final def provider: akka.actor.ActorRefProvider = system.provider
protected def uid: Int = self.path.uid
private[this] var _actor: Actor = _
@@ -398,9 +398,9 @@ private[akka] class ActorCell(
private[this] var sysmsgStash: LatestFirstSystemMessageList = SystemMessageList.LNil
// Java API
- final def getParent() = parent
+ final def getParent(): akka.actor.InternalActorRef = parent
// Java API
- final def getSystem() = system
+ final def getSystem(): akka.actor.ActorSystemImpl = system
protected def stash(msg: SystemMessage): Unit = {
assert(msg.unlinked)
@@ -408,7 +408,7 @@ private[akka] class ActorCell(
}
private def unstashAll(): LatestFirstSystemMessageList = {
- val unstashed = sysmsgStash
+ val unstashed: akka.dispatch.sysmsg.LatestFirstSystemMessageList = sysmsgStash
sysmsgStash = SystemMessageList.LNil
unstashed
}
@@ -435,8 +435,8 @@ private[akka] class ActorCell(
@tailrec def sendAllToDeadLetters(messages: EarliestFirstSystemMessageList): Unit =
if (messages.nonEmpty) {
- val tail = messages.tail
- val msg = messages.head
+ val tail: akka.dispatch.sysmsg.EarliestFirstSystemMessageList = messages.tail
+ val msg: akka.dispatch.sysmsg.SystemMessage = messages.head
msg.unlink()
provider.deadLetters ! msg
sendAllToDeadLetters(tail)
@@ -451,8 +451,8 @@ private[akka] class ActorCell(
@tailrec
def invokeAll(messages: EarliestFirstSystemMessageList, currentState: Int): Unit = {
- val rest = messages.tail
- val message = messages.head
+ val rest: akka.dispatch.sysmsg.EarliestFirstSystemMessageList = messages.tail
+ val message: akka.dispatch.sysmsg.SystemMessage = messages.head
message.unlink()
try {
message match {
@@ -472,10 +472,10 @@ private[akka] class ActorCell(
} catch handleNonFatalOrInterruptedException { e ⇒
handleInvokeFailure(Nil, e)
}
- val newState = calculateState
+ val newState: Int = calculateState
// As each state accepts a strict subset of another state, it is enough to unstash if we "walk up" the state
// chain
- val todo = if (newState < currentState) unstashAll() reverse_::: rest else rest
+ val todo: akka.dispatch.sysmsg.EarliestFirstSystemMessageList = if (newState < currentState) unstashAll() reverse_::: rest else rest
if (isTerminated) sendAllToDeadLetters(todo)
else if (todo.nonEmpty) invokeAll(todo, newState)
@@ -486,7 +486,7 @@ private[akka] class ActorCell(
//Memory consistency is handled by the Mailbox (reading mailbox status then processing messages, then writing mailbox status
final def invoke(messageHandle: Envelope): Unit = {
- val influenceReceiveTimeout = !messageHandle.message.isInstanceOf[NotInfluenceReceiveTimeout]
+ val influenceReceiveTimeout: Boolean = !messageHandle.message.isInstanceOf[NotInfluenceReceiveTimeout]
try {
currentMessage = messageHandle
if (influenceReceiveTimeout)
@@ -545,7 +545,7 @@ private[akka] class ActorCell(
become({ case msg ⇒ behavior.apply(msg) }: Actor.Receive, discardOld)
def unbecome(): Unit = {
- val original = behaviorStack
+ val original: List[akka.actor.Actor.Receive] = behaviorStack
behaviorStack =
if (original.isEmpty || original.tail.isEmpty) actor.receive :: emptyBehaviorStack
else original.tail
@@ -560,7 +560,7 @@ private[akka] class ActorCell(
contextStack.set(this :: contextStack.get)
try {
behaviorStack = emptyBehaviorStack
- val instance = props.newActor()
+ val instance: akka.actor.Actor = props.newActor()
if (instance eq null)
throw ActorInitializationException(self, "Actor instance passed to actorOf can't be 'null'")
@@ -569,7 +569,7 @@ private[akka] class ActorCell(
behaviorStack = if (behaviorStack.isEmpty) instance.receive :: behaviorStack else behaviorStack
instance
} finally {
- val stackAfter = contextStack.get
+ val stackAfter: List[akka.actor.ActorContext] = contextStack.get
if (stackAfter.nonEmpty)
contextStack.set(if (stackAfter.head eq null) stackAfter.tail.tail else stackAfter.tail) // pop null marker plus our context
}
@@ -586,7 +586,7 @@ private[akka] class ActorCell(
failure foreach { throw _ }
try {
- val created = newActor()
+ val created: akka.actor.Actor = newActor()
actor = created
created.aroundPreStart()
checkReceiveTimeout
diff --git a/akka-actor/src/main/scala/akka/actor/ActorDSL.scala b/akka-actor/src/main/scala/akka/actor/ActorDSL.scala
index 642e9a6..c057e42 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorDSL.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorDSL.scala
@@ -73,7 +73,7 @@ object ActorDSL extends dsl.Inbox with dsl.Creators {
protected object Extension extends ExtensionId[Extension] with ExtensionIdProvider {
- override def lookup = Extension
+ override def lookup: akka.actor.ActorDSL.Extension.type = Extension
override def createExtension(system: ExtendedActorSystem): Extension = new Extension(system)
@@ -88,21 +88,21 @@ object ActorDSL extends dsl.Inbox with dsl.Creators {
private case class MkChild(props: Props, name: String) extends NoSerializationVerificationNeeded
private val boss = system.systemActorOf(Props(
new Actor {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case MkChild(props, name) ⇒ sender() ! context.actorOf(props, name)
case any ⇒ sender() ! any
}
}), "dsl").asInstanceOf[RepointableActorRef]
- lazy val config = system.settings.config.getConfig("akka.actor.dsl")
+ lazy val config: com.typesafe.config.Config = system.settings.config.getConfig("akka.actor.dsl")
- val DSLDefaultTimeout = config.getMillisDuration("default-timeout")
+ val DSLDefaultTimeout: scala.concurrent.duration.FiniteDuration = config.getMillisDuration("default-timeout")
def mkChild(p: Props, name: String): ActorRef =
if (boss.isStarted)
boss.underlying.asInstanceOf[ActorCell].attachChild(p, name, systemService = true)
else {
- implicit val timeout = system.settings.CreationTimeout
+ implicit val timeout: akka.util.Timeout = system.settings.CreationTimeout
Await.result(boss ? MkChild(p, name), timeout.duration).asInstanceOf[ActorRef]
}
}
diff --git a/akka-actor/src/main/scala/akka/actor/ActorPath.scala b/akka-actor/src/main/scala/akka/actor/ActorPath.scala
index 30ee513..417b295 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorPath.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorPath.scala
@@ -79,7 +79,7 @@ object ActorPath {
* @param fullPath optional fullPath element that may be included for better error messages; null if not given
*/
final def validatePathElement(element: String, fullPath: String): Unit = {
- def fullPathMsg = if (fullPath ne null) s""" (in path [$fullPath])""" else ""
+ def fullPathMsg: String = if (fullPath ne null) s""" (in path [$fullPath])""" else ""
(findInvalidPathElementCharPosition(element): @switch) match {
case ValidPathCode ⇒
@@ -112,7 +112,7 @@ object ActorPath {
def isHexChar(c: Char): Boolean =
(c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9')
- val len = s.length
+ val len: Int = s.length
def validate(pos: Int): Int =
if (pos < len)
s.charAt(pos) match {
@@ -337,13 +337,13 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
else new ChildActorPath(parent, name, uid)
override def toString: String = {
- val length = toStringLength
+ val length: Int = toStringLength
buildToString(new JStringBuilder(length), length, 0, _.toString).toString
}
override def toSerializationFormat: String = {
- val length = toStringLength
- val sb = buildToString(new JStringBuilder(length + 12), length, 0, _.toString)
+ val length: Int = toStringLength
+ val sb: StringBuilder = buildToString(new JStringBuilder(length + 12), length, 0, _.toString)
appendUidFragment(sb).toString
}
@@ -355,20 +355,20 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
}
override def toStringWithAddress(addr: Address): String = {
- val diff = addressStringLengthDiff(addr)
- val length = toStringLength + diff
+ val diff: Int = addressStringLengthDiff(addr)
+ val length: Int = toStringLength + diff
buildToString(new JStringBuilder(length), length, diff, _.toStringWithAddress(addr)).toString
}
override def toSerializationFormatWithAddress(addr: Address): String = {
- val diff = addressStringLengthDiff(addr)
- val length = toStringLength + diff
- val sb = buildToString(new JStringBuilder(length + 12), length, diff, _.toStringWithAddress(addr))
+ val diff: Int = addressStringLengthDiff(addr)
+ val length: Int = toStringLength + diff
+ val sb: StringBuilder = buildToString(new JStringBuilder(length + 12), length, diff, _.toStringWithAddress(addr))
appendUidFragment(sb).toString
}
private def addressStringLengthDiff(addr: Address): Int = {
- val r = root
+ val r: akka.actor.RootActorPath = root
if (r.address.host.isDefined) 0
else (addr.toString.length - r.address.toString.length)
}
@@ -387,11 +387,11 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
@tailrec
def rec(p: ActorPath): JStringBuilder = p match {
case r: RootActorPath ⇒
- val rootStr = rootString(r)
+ val rootStr: String = rootString(r)
sb.replace(0, rootStr.length, rootStr)
case c: ChildActorPath ⇒
- val start = c.toStringOffset + diff
- val end = start + c.name.length
+ val start: Int = c.toStringOffset + diff
+ val end: Int = start + c.name.length
sb.replace(start, end, c.name)
if (c ne this)
sb.replace(end, end + 1, "/")
@@ -441,7 +441,7 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
else if (left.isInstanceOf[RootActorPath]) left compareTo right
else if (right.isInstanceOf[RootActorPath]) -(right compareTo left)
else {
- val x = left.name compareTo right.name
+ val x: Int = left.name compareTo right.name
if (x == 0) rec(left.parent, right.parent)
else x
}
diff --git a/akka-actor/src/main/scala/akka/actor/ActorRef.scala b/akka-actor/src/main/scala/akka/actor/ActorRef.scala
index 9d9d9e9..f5aec99 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorRef.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorRef.scala
@@ -109,8 +109,8 @@ abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable
/**
* Comparison takes path and the unique id of the actor cell into account.
*/
- final def compareTo(other: ActorRef) = {
- val x = this.path compareTo other.path
+ final def compareTo(other: ActorRef): Int = {
+ val x: Int = this.path compareTo other.path
if (x == 0) if (this.path.uid < other.path.uid) -1 else if (this.path.uid == other.path.uid) 0 else 1
else x
}
@@ -128,7 +128,7 @@ abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable
*
* Works, no matter whether originally sent with tell/'!' or ask/'?'.
*/
- def forward(message: Any)(implicit context: ActorContext) = tell(message, context.sender())
+ def forward(message: Any)(implicit context: ActorContext): Unit = tell(message, context.sender())
/**
* INTERNAL API
@@ -276,7 +276,7 @@ private[akka] abstract class ActorRefWithCell extends InternalActorRef { this: A
*/
private[akka] case object Nobody extends MinimalActorRef {
override val path: RootActorPath = new RootActorPath(Address("akka", "all-systems"), "/Nobody")
- override def provider = throw new UnsupportedOperationException("Nobody does not provide")
+ override def provider: Nothing = throw new UnsupportedOperationException("Nobody does not provide")
private val serialized = new SerializedNobody
@@ -377,7 +377,7 @@ private[akka] class LocalActorRef private[akka] (
def rec(ref: InternalActorRef, name: Iterator[String]): InternalActorRef =
ref match {
case l: LocalActorRef ⇒
- val next = name.next() match {
+ val next: akka.actor.InternalActorRef = name.next() match {
case ".." ⇒ l.getParent
case "" ⇒ l
case any ⇒ l.getSingleChild(any)
@@ -507,7 +507,7 @@ private[akka] object DeadLetterActorRef {
private def readResolve(): AnyRef = JavaSerializer.currentSystem.value.deadLetters
}
- val serialized = new SerializedDeadLetterActorRef
+ val serialized: akka.actor.DeadLetterActorRef.SerializedDeadLetterActorRef = new SerializedDeadLetterActorRef
}
/**
@@ -616,7 +616,7 @@ private[akka] class VirtualPathContainer(
case sel @ ActorSelectionMessage(msg, elements, wildcardFanOut) ⇒ {
require(elements.nonEmpty)
- def emptyRef = new EmptyLocalActorRef(provider, path / sel.elements.map(_.toString),
+ def emptyRef: akka.actor.EmptyLocalActorRef = new EmptyLocalActorRef(provider, path / sel.elements.map(_.toString),
provider.systemGuardian.underlying.system.eventStream)
elements.head match {
@@ -658,7 +658,7 @@ private[akka] class VirtualPathContainer(
* Remove a named child if it matches the ref.
*/
protected def removeChild(name: String, ref: ActorRef): Unit = {
- val current = getChild(name)
+ val current: akka.actor.InternalActorRef = getChild(name)
if (current eq null)
log.warning("{} trying to remove non-child {}", path, name)
else if (current == ref)
@@ -671,7 +671,7 @@ private[akka] class VirtualPathContainer(
override def getChild(name: Iterator[String]): InternalActorRef = {
if (name.isEmpty) this
else {
- val n = name.next()
+ val n: String = name.next()
if (n.isEmpty) this
else children.get(n) match {
case null ⇒ Nobody
@@ -685,7 +685,7 @@ private[akka] class VirtualPathContainer(
def hasChildren: Boolean = !children.isEmpty
def foreachChild(f: ActorRef ⇒ Unit): Unit = {
- val iter = children.values.iterator
+ val iter: java.util.Iterator[akka.actor.InternalActorRef] = children.values.iterator
while (iter.hasNext) f(iter.next)
}
}
@@ -728,11 +728,11 @@ private[akka] final class FunctionRef(
private[this] var watching = ActorCell.emptyActorRefSet
private[this] val _watchedBy = new AtomicReference[Set[ActorRef]](ActorCell.emptyActorRefSet)
- override def isTerminated = _watchedBy.get() == null
+ override def isTerminated: Boolean = _watchedBy.get() == null
//noinspection EmptyCheck
protected def sendTerminated(): Unit = {
- val watchedBy = _watchedBy.getAndSet(null)
+ val watchedBy: Set[akka.actor.ActorRef] = _watchedBy.getAndSet(null)
if (watchedBy != null) {
if (watchedBy.nonEmpty) {
watchedBy foreach sendTerminated(ifLocal = false)
@@ -761,8 +761,8 @@ private[akka] final class FunctionRef(
sendTerminated(ifLocal = false)(watcher)
case watchedBy ⇒
- val watcheeSelf = watchee == this
- val watcherSelf = watcher == this
+ val watcheeSelf: Boolean = watchee == this
+ val watcherSelf: Boolean = watcher == this
if (watcheeSelf && !watcherSelf) {
if (!watchedBy.contains(watcher))
@@ -779,8 +779,8 @@ private[akka] final class FunctionRef(
_watchedBy.get() match {
case null ⇒ // do nothing...
case watchedBy ⇒
- val watcheeSelf = watchee == this
- val watcherSelf = watcher == this
+ val watcheeSelf: Boolean = watchee == this
+ val watcherSelf: Boolean = watcher == this
if (watcheeSelf && !watcherSelf) {
if (watchedBy.contains(watcher))
diff --git a/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala b/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala
index dd83b06..5a512aa 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala
@@ -394,7 +394,7 @@ private[akka] object LocalActorRefProvider {
private class Guardian(override val supervisorStrategy: SupervisorStrategy) extends Actor
with RequiresMessageQueue[UnboundedMessageQueueSemantics] {
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Terminated(_) ⇒ context.stop(self)
case StopChild(child) ⇒ context.stop(child)
}
@@ -410,9 +410,9 @@ private[akka] object LocalActorRefProvider {
extends Actor with RequiresMessageQueue[UnboundedMessageQueueSemantics] {
import SystemGuardian._
- var terminationHooks = Set.empty[ActorRef]
+ var terminationHooks: scala.collection.immutable.Set[akka.actor.ActorRef] = Set.empty[ActorRef]
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Terminated(`guardian`) ⇒
// time for the systemGuardian to stop, but first notify all the
// termination hooks, they will reply with TerminationHookDone
@@ -509,11 +509,11 @@ private[akka] class LocalActorRefProvider private[akka] (
private[akka] val theOneWhoWalksTheBubblesOfSpaceTime: InternalActorRef = new MinimalActorRef {
val causeOfTermination: Promise[Terminated] = Promise[Terminated]()
- val path = rootPath / "bubble-walker"
+ val path: akka.actor.ActorPath = rootPath / "bubble-walker"
def provider: ActorRefProvider = LocalActorRefProvider.this
- def isWalking = causeOfTermination.future.isCompleted == false
+ def isWalking: Boolean = causeOfTermination.future.isCompleted == false
override def stop(): Unit = {
causeOfTermination.trySuccess(Terminated(provider.rootGuardian)(existenceConfirmed = true, addressTerminated = true)) //Idempotent
@@ -611,9 +611,9 @@ private[akka] class LocalActorRefProvider private[akka] (
else deadLetters
override lazy val guardian: LocalActorRef = {
- val cell = rootGuardian.underlying
+ val cell: akka.actor.ActorCell = rootGuardian.underlying
cell.reserveChild("user")
- val ref = new LocalActorRef(system, system.guardianProps.getOrElse(Props(classOf[LocalActorRefProvider.Guardian], guardianStrategy)),
+ val ref: akka.actor.LocalActorRef = new LocalActorRef(system, system.guardianProps.getOrElse(Props(classOf[LocalActorRefProvider.Guardian], guardianStrategy)),
defaultDispatcher, defaultMailbox, rootGuardian, rootPath / "user")
cell.initChild(ref)
ref.start()
@@ -621,9 +621,9 @@ private[akka] class LocalActorRefProvider private[akka] (
}
override lazy val systemGuardian: LocalActorRef = {
- val cell = rootGuardian.underlying
+ val cell: akka.actor.ActorCell = rootGuardian.underlying
cell.reserveChild("system")
- val ref = new LocalActorRef(
+ val ref: akka.actor.LocalActorRef = new LocalActorRef(
system, Props(classOf[LocalActorRefProvider.SystemGuardian], systemGuardianStrategy, guardian),
defaultDispatcher, defaultMailbox, rootGuardian, rootPath / "system")
cell.initChild(ref)
@@ -631,7 +631,7 @@ private[akka] class LocalActorRefProvider private[akka] (
ref
}
- lazy val tempContainer = new VirtualPathContainer(system.provider, tempNode, rootGuardian, log)
+ lazy val tempContainer: akka.actor.VirtualPathContainer = new VirtualPathContainer(system.provider, tempNode, rootGuardian, log)
def registerTempActor(actorRef: InternalActorRef, path: ActorPath): Unit = {
assert(path.parent eq tempNode, "cannot registerTempActor() with anything not obtained from tempPath()")
@@ -727,7 +727,7 @@ private[akka] class LocalActorRefProvider private[akka] (
}
val props2 =
- // mailbox and dispatcher defined in deploy should override props
+ // mailbox and dispatcher defined in deploy should override props: akka.actor.Props
(if (lookupDeploy) deployer.lookup(path) else deploy) match {
case Some(d) ⇒
(d.dispatcher, d.mailbox) match {
@@ -743,8 +743,8 @@ private[akka] class LocalActorRefProvider private[akka] (
throw new ConfigurationException(s"Dispatcher [${props2.dispatcher}] not configured for path $path")
try {
- val dispatcher = system.dispatchers.lookup(props2.dispatcher)
- val mailboxType = system.mailboxes.getMailboxType(props2, dispatcher.configurator.config)
+ val dispatcher: akka.dispatch.MessageDispatcher = system.dispatchers.lookup(props2.dispatcher)
+ val mailboxType: akka.dispatch.MailboxType = system.mailboxes.getMailboxType(props2, dispatcher.configurator.config)
if (async) new RepointableActorRef(system, props2, dispatcher, mailboxType, supervisor, path).initialize(async)
else new LocalActorRef(system, props2, dispatcher, mailboxType, supervisor, path)
@@ -754,28 +754,28 @@ private[akka] class LocalActorRefProvider private[akka] (
}
case router ⇒
- val lookup = if (lookupDeploy) deployer.lookup(path) else None
- val r = router :: deploy.map(_.routerConfig).toList ::: lookup.map(_.routerConfig).toList reduce ((a, b) ⇒ b withFallback a)
- val p = props.withRouter(r)
+ val lookup: Option[akka.actor.Deploy] = if (lookupDeploy) deployer.lookup(path) else None
+ val r: akka.routing.RouterConfig = router :: deploy.map(_.routerConfig).toList ::: lookup.map(_.routerConfig).toList reduce ((a, b) ⇒ b withFallback a)
+ val p: akka.actor.Props = props.withRouter(r)
if (!system.dispatchers.hasDispatcher(p.dispatcher))
throw new ConfigurationException(s"Dispatcher [${p.dispatcher}] not configured for routees of $path")
if (!system.dispatchers.hasDispatcher(r.routerDispatcher))
throw new ConfigurationException(s"Dispatcher [${p.dispatcher}] not configured for router of $path")
- val routerProps = Props(
+ val routerProps: akka.actor.Props = Props(
p.deploy.copy(dispatcher = p.routerConfig.routerDispatcher),
classOf[RoutedActorCell.RouterActorCreator], Vector(p.routerConfig))
- val routeeProps = p.withRouter(NoRouter)
+ val routeeProps: akka.actor.Props = p.withRouter(NoRouter)
try {
- val routerDispatcher = system.dispatchers.lookup(p.routerConfig.routerDispatcher)
- val routerMailbox = system.mailboxes.getMailboxType(routerProps, routerDispatcher.configurator.config)
+ val routerDispatcher: akka.dispatch.MessageDispatcher = system.dispatchers.lookup(p.routerConfig.routerDispatcher)
+ val routerMailbox: akka.dispatch.MailboxType = system.mailboxes.getMailboxType(routerProps, routerDispatcher.configurator.config)
// routers use context.actorOf() to create the routees, which does not allow us to pass
// these through, but obtain them here for early verification
- val routeeDispatcher = system.dispatchers.lookup(p.dispatcher)
- val routeeMailbox = system.mailboxes.getMailboxType(routeeProps, routeeDispatcher.configurator.config)
+ val routeeDispatcher: akka.dispatch.MessageDispatcher = system.dispatchers.lookup(p.dispatcher)
+ val routeeMailbox: akka.dispatch.MailboxType = system.mailboxes.getMailboxType(routeeProps, routeeDispatcher.configurator.config)
new RoutedActorRef(system, routerProps, routerDispatcher, routerMailbox, routeeProps, supervisor, path).initialize(async)
} catch {
diff --git a/akka-actor/src/main/scala/akka/actor/ActorSelection.scala b/akka-actor/src/main/scala/akka/actor/ActorSelection.scala
index b8623a3..2b05c1d 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorSelection.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorSelection.scala
@@ -50,7 +50,7 @@ abstract class ActorSelection extends Serializable {
*
* Works, no matter whether originally sent with tell/'!' or ask/'?'.
*/
- def forward(message: Any)(implicit context: ActorContext) = tell(message, context.sender())
+ def forward(message: Any)(implicit context: ActorContext): Unit = tell(message, context.sender())
/**
* Resolve the [[ActorRef]] matching this selection.
@@ -63,8 +63,8 @@ abstract class ActorSelection extends Serializable {
* [[ActorRef]].
*/
def resolveOne()(implicit timeout: Timeout): Future[ActorRef] = {
- implicit val ec = ExecutionContexts.sameThreadExecutionContext
- val p = Promise[ActorRef]()
+ implicit val ec: akka.dispatch.ExecutionContexts.sameThreadExecutionContext.type = ExecutionContexts.sameThreadExecutionContext
+ val p: scala.concurrent.Promise[akka.actor.ActorRef] = Promise[ActorRef]()
this.ask(Identify(None)) onComplete {
case Success(ActorIdentity(_, Some(ref))) ⇒ p.success(ref)
case _ ⇒ p.failure(ActorNotFound(this))
@@ -98,7 +98,7 @@ abstract class ActorSelection extends Serializable {
FutureConverters.toJava[ActorRef](resolveOne(timeout))
override def toString: String = {
- val builder = new java.lang.StringBuilder()
+ val builder: StringBuilder = new java.lang.StringBuilder()
builder.append("ActorSelection[Anchor(").append(anchor.path)
if (anchor.path.uid != ActorCell.undefinedUid)
builder.append("#").append(anchor.path.uid)
@@ -123,14 +123,14 @@ abstract class ActorSelection extends Serializable {
* @return URI fragment
*/
def toSerializationFormat: String = {
- val anchorPath = anchor match {
+ val anchorPath: String = anchor match {
case a: ActorRefWithCell ⇒ anchor.path.toStringWithAddress(a.provider.getDefaultAddress)
case _ ⇒ anchor.path.toString
}
- val builder = new java.lang.StringBuilder()
+ val builder: StringBuilder = new java.lang.StringBuilder()
builder.append(anchorPath)
- val lastChar = builder.charAt(builder.length - 1)
+ val lastChar: Char = builder.charAt(builder.length - 1)
if (path.nonEmpty && lastChar != '/')
builder.append(path.mkString("/", "/", ""))
else if (path.nonEmpty)
@@ -181,8 +181,8 @@ object ActorSelection {
else SelectChildName(x)
})(scala.collection.breakOut)
new ActorSelection with ScalaActorSelection {
- override val anchor = anchorRef
- override val path = compiled
+ override val anchor: akka.actor.ActorRef = anchorRef
+ override val path: scala.collection.immutable.IndexedSeq[akka.actor.SelectionPathElement] = compiled
}
}
@@ -196,24 +196,24 @@ object ActorSelection {
anchor.tell(sel.msg, sender)
else {
- val iter = sel.elements.iterator
+ val iter: Iterator[akka.actor.SelectionPathElement] = sel.elements.iterator
@tailrec def rec(ref: InternalActorRef): Unit = {
ref match {
case refWithCell: ActorRefWithCell ⇒
- def emptyRef = new EmptyLocalActorRef(refWithCell.provider, anchor.path / sel.elements.map(_.toString),
+ def emptyRef: akka.actor.EmptyLocalActorRef = new EmptyLocalActorRef(refWithCell.provider, anchor.path / sel.elements.map(_.toString),
refWithCell.underlying.system.eventStream)
iter.next() match {
case SelectParent ⇒
- val parent = ref.getParent
+ val parent: akka.actor.InternalActorRef = ref.getParent
if (iter.isEmpty)
parent.tell(sel.msg, sender)
else
rec(parent)
case SelectChildName(name) ⇒
- val child = refWithCell.getSingleChild(name)
+ val child: akka.actor.InternalActorRef = refWithCell.getSingleChild(name)
if (child == Nobody) {
// don't send to emptyRef after wildcard fan-out
if (!sel.wildcardFanOut) emptyRef.tell(sel, sender)
@@ -223,21 +223,21 @@ object ActorSelection {
rec(child)
case p: SelectChildPattern ⇒
// fan-out when there is a wildcard
- val chldr = refWithCell.children
+ val chldr: scala.collection.immutable.Iterable[akka.actor.ActorRef] = refWithCell.children
if (iter.isEmpty) {
// leaf
- val matchingChildren = chldr.filter(c ⇒ p.pattern.matcher(c.path.name).matches)
+ val matchingChildren: scala.collection.immutable.Iterable[akka.actor.ActorRef] = chldr.filter(c ⇒ p.pattern.matcher(c.path.name).matches)
if (matchingChildren.isEmpty && !sel.wildcardFanOut)
emptyRef.tell(sel, sender)
else
matchingChildren.foreach(_.tell(sel.msg, sender))
} else {
- val matchingChildren = chldr.filter(c ⇒ p.pattern.matcher(c.path.name).matches)
+ val matchingChildren: scala.collection.immutable.Iterable[akka.actor.ActorRef] = chldr.filter(c ⇒ p.pattern.matcher(c.path.name).matches)
// don't send to emptyRef after wildcard fan-out
if (matchingChildren.isEmpty && !sel.wildcardFanOut)
emptyRef.tell(sel, sender)
else {
- val m = sel.copy(
+ val m: akka.actor.ActorSelectionMessage = sel.copy(
elements = iter.toVector,
wildcardFanOut = sel.wildcardFanOut || matchingChildren.size > 1)
matchingChildren.foreach(c ⇒ deliverSelection(c.asInstanceOf[InternalActorRef], sender, m))
@@ -262,7 +262,7 @@ object ActorSelection {
trait ScalaActorSelection {
this: ActorSelection ⇒
- def !(msg: Any)(implicit sender: ActorRef = Actor.noSender) = tell(msg, sender)
+ def !(msg: Any)(implicit sender: ActorRef = Actor.noSender): Unit = tell(msg, sender)
}
/**
diff --git a/akka-actor/src/main/scala/akka/actor/ActorSystem.scala b/akka-actor/src/main/scala/akka/actor/ActorSystem.scala
index c2c47b3..e917107 100644
--- a/akka-actor/src/main/scala/akka/actor/ActorSystem.scala
+++ b/akka-actor/src/main/scala/akka/actor/ActorSystem.scala
@@ -236,10 +236,10 @@ object ActorSystem {
* The core actor system settings are defined in [[BootstrapSetup]]
*/
def apply(name: String, setup: ActorSystemSetup): ActorSystem = {
- val bootstrapSettings = setup.get[BootstrapSetup]
- val cl = bootstrapSettings.flatMap(_.classLoader).getOrElse(findClassLoader())
- val appConfig = bootstrapSettings.flatMap(_.config).getOrElse(ConfigFactory.load(cl))
- val defaultEC = bootstrapSettings.flatMap(_.defaultExecutionContext)
+ val bootstrapSettings: Option[akka.actor.BootstrapSetup] = setup.get[BootstrapSetup]
+ val cl: ClassLoader = bootstrapSettings.flatMap(_.classLoader).getOrElse(findClassLoader())
+ val appConfig: com.typesafe.config.Config = bootstrapSettings.flatMap(_.config).getOrElse(ConfigFactory.load(cl))
+ val defaultEC: Option[scala.concurrent.ExecutionContext] = bootstrapSettings.flatMap(_.defaultExecutionContext)
new ActorSystemImpl(name, appConfig, cl, defaultEC, None, setup).start()
}
@@ -303,7 +303,7 @@ object ActorSystem {
* @see <a href="http://typesafehub.github.io/config/v1.3.1/" target="_blank">The Typesafe Config Library API Documentation</a>
*/
final val config: Config = {
- val config = cfg.withFallback(ConfigFactory.defaultReference(classLoader))
+ val config: com.typesafe.config.Config = cfg.withFallback(ConfigFactory.defaultReference(classLoader))
config.checkValid(ConfigFactory.defaultReference(classLoader), "akka")
config
}
@@ -723,9 +723,9 @@ private[akka] class ActorSystemImpl(
else throw new UnsupportedOperationException("cannot create top-level actor from the outside on ActorSystem with custom user guardian")
def stop(actor: ActorRef): Unit = {
- val path = actor.path
- val guard = guardian.path
- val sys = systemGuardian.path
+ val path: akka.actor.ActorPath = actor.path
+ val guard: akka.actor.ActorPath = guardian.path
+ val sys: akka.actor.ActorPath = systemGuardian.path
path.parent match {
case `guard` ⇒ guardian ! StopChild(actor)
case `sys` ⇒ systemGuardian ! StopChild(actor)
@@ -736,11 +736,11 @@ private[akka] class ActorSystemImpl(
import settings._
// this provides basic logging (to stdout) until .start() is called below
- val eventStream = new EventStream(this, DebugEventStream)
+ val eventStream: akka.event.EventStream = new EventStream(this, DebugEventStream)
eventStream.startStdoutLogger(settings)
val logFilter: LoggingFilter = {
- val arguments = Vector(classOf[Settings] → settings, classOf[EventStream] → eventStream)
+ val arguments: scala.collection.immutable.Vector[(Class[_ >: akka.event.EventStream with akka.actor.ActorSystem.Settings <: Object], Object)] = Vector(classOf[Settings] → settings, classOf[EventStream] → eventStream)
dynamicAccess.createInstanceFor[LoggingFilter](LoggingFilter, arguments).get
}
@@ -750,7 +750,7 @@ private[akka] class ActorSystemImpl(
val scheduler: Scheduler = createScheduler()
val provider: ActorRefProvider = try {
- val arguments = Vector(
+ val arguments: scala.collection.immutable.Vector[(Class[_ >: akka.actor.DynamicAccess with akka.event.EventStream with akka.actor.ActorSystem.Settings with String <: Object], Object)] = Vector(
classOf[String] → name,
classOf[Settings] → settings,
classOf[EventStream] → eventStream,
@@ -807,7 +807,7 @@ private[akka] class ActorSystemImpl(
}
def start(): this.type = _start
- def registerOnTermination[T](code: ⇒ T) { registerOnTermination(new Runnable { def run = code }) }
+ def registerOnTermination[T](code: ⇒ T) { registerOnTermination(new Runnable { def run: Unit = code }) }
def registerOnTermination(code: Runnable) { terminationCallbacks.add(code) }
override def terminate(): Future[Terminated] = {
@@ -874,7 +874,7 @@ private[akka] class ActorSystemImpl(
final def registerExtension[T <: Extension](ext: ExtensionId[T]): T = {
findExtension(ext) match {
case null ⇒ //Doesn't already exist, commence registration
- val inProcessOfRegistration = new CountDownLatch(1)
+ val inProcessOfRegistration: java.util.concurrent.CountDownLatch = new CountDownLatch(1)
extensions.putIfAbsent(ext, inProcessOfRegistration) match { // Signal that registration is in process
case null ⇒ try { // Signal was successfully sent
ext.createExtension(this) match { // Create and initialize the extension
@@ -935,7 +935,7 @@ private[akka] class ActorSystemImpl(
def printNode(node: ActorRef, indent: String): String = {
node match {
case wc: ActorRefWithCell ⇒
- val cell = wc.underlying
+ val cell: akka.actor.Cell = wc.underlying
(if (indent.isEmpty) "-> " else indent.dropRight(1) + "⌊-> ") +
node.path.name + " " + Logging.simpleName(node) + " " +
(cell match {
@@ -956,8 +956,8 @@ private[akka] class ActorSystemImpl(
}) +
(if (cell.childrenRefs.children.isEmpty) "" else "\n") +
({
- val children = cell.childrenRefs.children.toSeq.sorted
- val bulk = children.dropRight(1) map (printNode(_, indent + " |"))
+ val children: Seq[akka.actor.ActorRef] = cell.childrenRefs.children.toSeq.sorted
+ val bulk: Seq[String] = children.dropRight(1) map (printNode(_, indent + " |"))
bulk ++ (children.lastOption map (printNode(_, indent + " ")))
} mkString ("\n"))
case _ ⇒
diff --git a/akka-actor/src/main/scala/akka/actor/Address.scala b/akka-actor/src/main/scala/akka/actor/Address.scala
index f83ed33..f4159b7 100644
--- a/akka-actor/src/main/scala/akka/actor/Address.scala
+++ b/akka-actor/src/main/scala/akka/actor/Address.scala
@@ -50,7 +50,7 @@ final case class Address private (protocol: String, system: String, host: Option
*/
@transient
override lazy val toString: String = {
- val sb = (new java.lang.StringBuilder(protocol)).append("://").append(system)
+ val sb: StringBuilder = (new java.lang.StringBuilder(protocol)).append("://").append(system)
if (host.isDefined) sb.append('@').append(host.get)
if (port.isDefined) sb.append(':').append(port.get)
@@ -70,12 +70,12 @@ object Address {
/**
* Constructs a new Address with the specified protocol and system name
*/
- def apply(protocol: String, system: String) = new Address(protocol, system)
+ def apply(protocol: String, system: String): akka.actor.Address = new Address(protocol, system)
/**
* Constructs a new Address with the specified protocol, system name, host and port
*/
- def apply(protocol: String, system: String, host: String, port: Int) = new Address(protocol, system, Some(host), Some(port))
+ def apply(protocol: String, system: String, host: String, port: Int): akka.actor.Address = new Address(protocol, system, Some(host), Some(port))
/**
* `Address` ordering type class, sorts addresses by protocol, name, host and port.
@@ -94,9 +94,9 @@ private[akka] trait PathUtils {
protected def split(s: String, fragment: String): List[String] = {
@tailrec
def rec(pos: Int, acc: List[String]): List[String] = {
- val from = s.lastIndexOf('/', pos - 1)
- val sub = s.substring(from + 1, pos)
- val l =
+ val from: Int = s.lastIndexOf('/', pos - 1)
+ val sub: String = s.substring(from + 1, pos)
+ val l: List[String] =
if ((fragment ne null) && acc.isEmpty) sub + "#" + fragment :: acc
else sub :: acc
if (from == -1) l else rec(from, l)
@@ -115,7 +115,7 @@ private[akka] trait PathUtils {
object RelativeActorPath extends PathUtils {
def unapply(addr: String): Option[immutable.Seq[String]] = {
try {
- val uri = new URI(addr)
+ val uri: java.net.URI = new URI(addr)
if (uri.isAbsolute) None
else Some(split(uri.getRawPath, uri.getRawFragment))
} catch {
@@ -163,7 +163,7 @@ object AddressFromURIString {
object ActorPathExtractor extends PathUtils {
def unapply(addr: String): Option[(Address, immutable.Iterable[String])] =
try {
- val uri = new URI(addr)
+ val uri: java.net.URI = new URI(addr)
uri.getRawPath match {
case null ⇒ None
case path ⇒ AddressFromURIString.unapply(uri).map((_, split(path, uri.getRawFragment).drop(1)))
diff --git a/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala b/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala
index 7e2f359..ca1b0f1 100644
--- a/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala
+++ b/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala
@@ -102,20 +102,20 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi
override def get(system: ActorSystem): CoordinatedShutdown = super.get(system)
- override def lookup = CoordinatedShutdown
+ override def lookup: akka.actor.CoordinatedShutdown.type = CoordinatedShutdown
override def createExtension(system: ExtendedActorSystem): CoordinatedShutdown = {
- val conf = system.settings.config.getConfig("akka.coordinated-shutdown")
- val phases = phasesFromConfig(conf)
- val coord = new CoordinatedShutdown(system, phases)
+ val conf: com.typesafe.config.Config = system.settings.config.getConfig("akka.coordinated-shutdown")
+ val phases: Map[String, akka.actor.CoordinatedShutdown.Phase] = phasesFromConfig(conf)
+ val coord: akka.actor.CoordinatedShutdown = new CoordinatedShutdown(system, phases)
initPhaseActorSystemTerminate(system, conf, coord)
initJvmHook(system, conf, coord)
coord
}
private def initPhaseActorSystemTerminate(system: ActorSystem, conf: Config, coord: CoordinatedShutdown): Unit = {
- val terminateActorSystem = conf.getBoolean("terminate-actor-system")
- val exitJvm = conf.getBoolean("exit-jvm")
+ val terminateActorSystem: Boolean = conf.getBoolean("terminate-actor-system")
+ val exitJvm: Boolean = conf.getBoolean("exit-jvm")
if (terminateActorSystem || exitJvm) {
coord.addTask(PhaseActorSystemTerminate, "terminate-system") { () ⇒
if (exitJvm && terminateActorSystem) {
@@ -123,8 +123,8 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi
// exit the JVM forcefully anyway.
// We must spawn a separate thread to not block current thread,
// since that would have blocked the shutdown of the ActorSystem.
- val timeout = coord.timeout(PhaseActorSystemTerminate)
- val t = new Thread {
+ val timeout: scala.concurrent.duration.FiniteDuration = coord.timeout(PhaseActorSystemTerminate)
+ val t: Thread = new Thread {
override def run(): Unit = {
if (Try(Await.ready(system.whenTerminated, timeout)).isFailure && !runningJvmHook)
System.exit(0)
@@ -149,7 +149,7 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi
}
private def initJvmHook(system: ActorSystem, conf: Config, coord: CoordinatedShutdown): Unit = {
- val runByJvmShutdownHook = conf.getBoolean("run-by-jvm-shutdown-hook")
+ val runByJvmShutdownHook: Boolean = conf.getBoolean("run-by-jvm-shutdown-hook")
if (runByJvmShutdownHook) {
coord.addJvmShutdownHook {
runningJvmHook = true // avoid System.exit from PhaseActorSystemTerminate task
@@ -157,7 +157,7 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi
coord.log.info("Starting coordinated shutdown from JVM shutdown hook")
try {
// totalTimeout will be 0 when no tasks registered, so at least 3.seconds
- val totalTimeout = coord.totalTimeout().max(3.seconds)
+ val totalTimeout: scala.concurrent.duration.FiniteDuration = coord.totalTimeout().max(3.seconds)
Await.ready(coord.run(), totalTimeout)
} catch {
case NonFatal(e) ⇒
@@ -180,19 +180,19 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi
*/
private[akka] def phasesFromConfig(conf: Config): Map[String, Phase] = {
import scala.collection.JavaConverters._
- val defaultPhaseTimeout = conf.getString("default-phase-timeout")
- val phasesConf = conf.getConfig("phases")
- val defaultPhaseConfig = ConfigFactory.parseString(s"""
+ val defaultPhaseTimeout: String = conf.getString("default-phase-timeout")
+ val phasesConf: com.typesafe.config.Config = conf.getConfig("phases")
+ val defaultPhaseConfig: com.typesafe.config.Config = ConfigFactory.parseString(s"""
timeout = $defaultPhaseTimeout
recover = true
depends-on = []
""")
phasesConf.root.unwrapped.asScala.toMap.map {
case (k, _: java.util.Map[_, _]) ⇒
- val c = phasesConf.getConfig(k).withFallback(defaultPhaseConfig)
- val dependsOn = c.getStringList("depends-on").asScala.toSet
- val timeout = c.getDuration("timeout", MILLISECONDS).millis
- val recover = c.getBoolean("recover")
+ val c: com.typesafe.config.Config = phasesConf.getConfig(k).withFallback(defaultPhaseConfig)
+ val dependsOn: scala.collection.immutable.Set[String] = c.getStringList("depends-on").asScala.toSet
+ val timeout: scala.concurrent.duration.FiniteDuration = c.getDuration("timeout", MILLISECONDS).millis
+ val recover: Boolean = c.getBoolean("recover")
k → Phase(dependsOn, timeout, recover)
case (k, v) ⇒
throw new IllegalArgumentException(s"Expected object value for [$k], got [$v]")
@@ -270,7 +270,7 @@ final class CoordinatedShutdown private[akka] (
knownPhases(phase),
s"Unknown phase [$phase], known phases [$knownPhases]. " +
"All phases (along with their optional dependencies) must be defined in configuration")
- val current = tasks.get(phase)
+ val current: Vector[(String, () ⇒ scala.concurrent.Future[akka.Done])] = tasks.get(phase)
if (current == null) {
if (tasks.putIfAbsent(phase, Vector(taskName → task)) != null)
addTask(phase, taskName)(task) // CAS failed, retry
@@ -323,12 +323,12 @@ final class CoordinatedShutdown private[akka] (
def run(fromPhase: Option[String]): Future[Done] = {
if (runStarted.compareAndSet(false, true)) {
import system.dispatcher
- val debugEnabled = log.isDebugEnabled
+ val debugEnabled: Boolean = log.isDebugEnabled
def loop(remainingPhases: List[String]): Future[Done] = {
remainingPhases match {
case Nil ⇒ Future.successful(Done)
case phase :: remaining ⇒
- val phaseResult = (tasks.get(phase) match {
+ val phaseResult: scala.concurrent.Future[akka.Done.type] = (tasks.get(phase) match {
case null ⇒
if (debugEnabled) log.debug("Performing phase [{}] with [0] tasks", phase)
Future.successful(Done)
@@ -337,11 +337,11 @@ final class CoordinatedShutdown private[akka] (
"Performing phase [{}] with [{}] tasks: [{}]",
phase, tasks.size, tasks.map { case (taskName, _) ⇒ taskName }.mkString(", "))
// note that tasks within same phase are performed in parallel
- val recoverEnabled = phases(phase).recover
- val result = Future.sequence(tasks.map {
+ val recoverEnabled: Boolean = phases(phase).recover
+ val result: scala.concurrent.Future[akka.Done.type] = Future.sequence(tasks.map {
case (taskName, task) ⇒
try {
- val r = task.apply()
+ val r: scala.concurrent.Future[akka.Done] = task.apply()
if (recoverEnabled) r.recover {
case NonFatal(e) ⇒
log.warning("Task [{}] failed in phase [{}]: {}", taskName, phase, e.getMessage)
@@ -358,9 +358,9 @@ final class CoordinatedShutdown private[akka] (
Future.failed(e)
}
}).map(_ ⇒ Done)(ExecutionContexts.sameThreadExecutionContext)
- val timeout = phases(phase).timeout
- val deadline = Deadline.now + timeout
- val timeoutFut = try {
+ val timeout: scala.concurrent.duration.FiniteDuration = phases(phase).timeout
+ val deadline: scala.concurrent.duration.Deadline = Deadline.now + timeout
+ val timeoutFut: scala.concurrent.Future[akka.Done.type] = try {
after(timeout, system.scheduler) {
if (phase == CoordinatedShutdown.PhaseActorSystemTerminate && deadline.hasTimeLeft) {
// too early, i.e. triggered by system termination
@@ -388,11 +388,11 @@ final class CoordinatedShutdown private[akka] (
}
}
- val remainingPhases = fromPhase match {
+ val remainingPhases: List[String] = fromPhase match {
case None ⇒ orderedPhases // all
case Some(p) ⇒ orderedPhases.dropWhile(_ != p)
}
- val done = loop(remainingPhases)
+ val done: scala.concurrent.Future[akka.Done] = loop(remainingPhases)
runPromise.completeWith(done)
}
runPromise.future
@@ -438,8 +438,8 @@ final class CoordinatedShutdown private[akka] (
*/
@tailrec def addJvmShutdownHook[T](hook: ⇒ T): Unit = {
if (!runStarted.get) {
- val currentLatch = _jvmHooksLatch.get
- val newLatch = new CountDownLatch(currentLatch.getCount.toInt + 1)
+ val currentLatch: java.util.concurrent.CountDownLatch = _jvmHooksLatch.get
+ val newLatch: java.util.concurrent.CountDownLatch = new CountDownLatch(currentLatch.getCount.toInt + 1)
if (_jvmHooksLatch.compareAndSet(currentLatch, newLatch)) {
try Runtime.getRuntime.addShutdownHook(new Thread {
override def run(): Unit = {
diff --git a/akka-actor/src/main/scala/akka/actor/Deployer.scala b/akka-actor/src/main/scala/akka/actor/Deployer.scala
index 1c58dc8..db3e1f9 100644
--- a/akka-actor/src/main/scala/akka/actor/Deployer.scala
+++ b/akka-actor/src/main/scala/akka/actor/Deployer.scala
@@ -15,7 +15,7 @@ import scala.annotation.tailrec
object Deploy {
final val NoDispatcherGiven = ""
final val NoMailboxGiven = ""
- val local = Deploy(scope = LocalScope)
+ val local: akka.actor.Deploy = Deploy(scope = LocalScope)
}
/**
@@ -104,7 +104,7 @@ case object LocalScope extends LocalScope {
/**
* Java API: get the singleton instance
*/
- def getInstance = this
+ def getInstance: akka.actor.LocalScope.type = this
def withFallback(other: Scope): Scope = this
}
@@ -121,7 +121,7 @@ case object NoScopeGiven extends NoScopeGiven {
/**
* Java API: get the singleton instance
*/
- def getInstance = this
+ def getInstance: akka.actor.NoScopeGiven.type = this
}
/**
@@ -134,7 +134,7 @@ private[akka] class Deployer(val settings: ActorSystem.Settings, val dynamicAcce
private val resizerEnabled: Config = ConfigFactory.parseString("resizer.enabled=on")
private val deployments = new AtomicReference(WildcardIndex[Deploy]())
private val config = settings.config.getConfig("akka.actor.deployment")
- protected val default = config.getConfig("default")
+ protected val default: com.typesafe.config.Config = config.getConfig("default")
val routerTypeMapping: Map[String, String] =
settings.config.getConfig("akka.actor.router.type-mapping").root.unwrapped.asScala.collect {
case (key, value: String) ⇒ (key → value)
@@ -164,10 +164,10 @@ private[akka] class Deployer(val settings: ActorSystem.Settings, val dynamicAcce
}
def parseConfig(key: String, config: Config): Option[Deploy] = {
- val deployment = config.withFallback(default)
- val router = createRouterConfig(deployment.getString("router"), key, config, deployment)
- val dispatcher = deployment.getString("dispatcher")
- val mailbox = deployment.getString("mailbox")
+ val deployment: com.typesafe.config.Config = config.withFallback(default)
+ val router: akka.routing.RouterConfig = createRouterConfig(deployment.getString("router"), key, config, deployment)
+ val dispatcher: String = deployment.getString("dispatcher")
+ val mailbox: String = deployment.getString("mailbox")
Some(Deploy(key, deployment, router, NoScopeGiven, dispatcher, mailbox))
}
@@ -182,22 +182,22 @@ private[akka] class Deployer(val settings: ActorSystem.Settings, val dynamicAcce
if (routerType == "from-code") NoRouter
else {
// need this for backwards compatibility, resizer enabled when including (parts of) resizer section in the deployment
- val deployment2 =
+ val deployment2: com.typesafe.config.Config =
if (config.hasPath("resizer") && !deployment.getBoolean("resizer.enabled"))
resizerEnabled.withFallback(deployment)
else deployment
- val fqn = routerTypeMapping.getOrElse(routerType, routerType)
+ val fqn: String = routerTypeMapping.getOrElse(routerType, routerType)
- def throwCannotInstantiateRouter(args: Seq[(Class[_], AnyRef)], cause: Throwable) =
+ def throwCannotInstantiateRouter(args: Seq[(Class[_], AnyRef)], cause: Throwable): Nothing =
throw new IllegalArgumentException(
s"Cannot instantiate router [$fqn], defined in [$key], " +
s"make sure it extends [${classOf[RouterConfig]}] and has constructor with " +
s"[${args(0)._1.getName}] and optional [${args(1)._1.getName}] parameter", cause)
// first try with Config param, and then with Config and DynamicAccess parameters
- val args1 = List(classOf[Config] → deployment2)
- val args2 = List(classOf[Config] → deployment2, classOf[DynamicAccess] → dynamicAccess)
+ val args1: List[(Class[com.typesafe.config.Config], com.typesafe.config.Config)] = List(classOf[Config] → deployment2)
+ val args2: List[(Class[_ >: akka.actor.DynamicAccess with com.typesafe.config.Config <: Object], Object)] = List(classOf[Config] → deployment2, classOf[DynamicAccess] → dynamicAccess)
dynamicAccess.createInstanceFor[RouterConfig](fqn, args1).recover({
case e @ (_: IllegalArgumentException | _: ConfigException) ⇒ throw e
case e: NoSuchMethodException ⇒
diff --git a/akka-actor/src/main/scala/akka/actor/FSM.scala b/akka-actor/src/main/scala/akka/actor/FSM.scala
index 9390b2d..cb7297a 100644
--- a/akka-actor/src/main/scala/akka/actor/FSM.scala
+++ b/akka-actor/src/main/scala/akka/actor/FSM.scala
@@ -23,7 +23,7 @@ object FSM {
*/
object NullFunction extends PartialFunction[Any, Nothing] {
def isDefinedAt(o: Any) = false
- def apply(o: Any) = sys.error("undefined")
+ def apply(o: Any): Nothing = sys.error("undefined")
}
/**
@@ -94,7 +94,7 @@ object FSM {
extends NoSerializationVerificationNeeded {
private var ref: Option[Cancellable] = _
private val scheduler = context.system.scheduler
- private implicit val executionContext = context.dispatcher
+ private implicit val executionContext: scala.concurrent.ExecutionContextExecutor = context.dispatcher
def schedule(actor: ActorRef, timeout: FiniteDuration): Unit =
ref = Some(
@@ -115,7 +115,7 @@ object FSM {
object `->` {
def unapply[S](in: (S, S)) = Some(in)
}
- val `→` = `->`
+ val `→`: akka.actor.FSM.`->`.type = `->`
/**
* Log Entry of the [[akka.actor.LoggingFSM]], can be obtained by calling `getLog`.
@@ -323,12 +323,12 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
* This extractor is just convenience for matching a (S, S) pair, including a
* reminder what the new state is.
*/
- val `->` = FSM.`->`
+ val `->`: akka.actor.FSM. → .type = FSM.`->`
/**
* This case object is received in case of a state timeout.
*/
- val StateTimeout = FSM.StateTimeout
+ val StateTimeout: akka.actor.FSM.StateTimeout.type = FSM.StateTimeout
/**
* ****************************************
@@ -421,7 +421,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
if (timers contains name) {
timers(name).cancel
}
- val timer = Timer(name, msg, repeat, timerGen.next, this)(context)
+ val timer: akka.actor.FSM.Timer = Timer(name, msg, repeat, timerGen.next, this)(context)
timer.schedule(self, timeout)
timers(name) = timer
}
@@ -541,7 +541,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
/**
* Return next state data (available in onTransition handlers)
*/
- final def nextStateData = nextState match {
+ final def nextStateData: D = nextState match {
case null ⇒ throw new IllegalStateException("nextStateData is only available during onTransition")
case x ⇒ x.stateData
}
@@ -604,7 +604,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
*/
private var transitionEvent: List[TransitionHandler] = Nil
private def handleTransition(prev: S, next: S) {
- val tuple = (prev, next)
+ val tuple: (S, S) = (prev, next)
for (te ← transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) }
}
@@ -655,13 +655,13 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
}
private def processMsg(value: Any, source: AnyRef): Unit = {
- val event = Event(value, currentState.stateData)
+ val event: akka.actor.FSM.Event[D] = Event(value, currentState.stateData)
processEvent(event, source)
}
private[akka] def processEvent(event: Event, source: AnyRef): Unit = {
- val stateFunc = stateFunctions(currentState.stateName)
- val nextState = if (stateFunc isDefinedAt event) {
+ val stateFunc: PartialFunction[akka.actor.FSM.Event[D], akka.actor.FSM.State[S, D]] = stateFunctions(currentState.stateName)
+ val nextState: akka.actor.FSM.State[S, D] = if (stateFunc isDefinedAt event) {
stateFunc(event)
} else {
// handleEventDefault ensures that this is always defined
@@ -702,7 +702,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
case SomeMaxFiniteDuration ⇒ // effectively disable stateTimeout
case Some(d: FiniteDuration) if d.length >= 0 ⇒ timeoutFuture = scheduleTimeout(d)
case _ ⇒
- val timeout = stateTimeouts(currentState.stateName)
+ val timeout: Option[scala.concurrent.duration.FiniteDuration] = stateTimeouts(currentState.stateName)
if (timeout.isDefined) timeoutFuture = scheduleTimeout(timeout.get)
}
}
@@ -727,14 +727,14 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
private def terminate(nextState: State): Unit = {
if (currentState.stopReason.isEmpty) {
- val reason = nextState.stopReason.get
+ val reason: akka.actor.FSM.Reason = nextState.stopReason.get
logTermination(reason)
for (timer ← timers.values) timer.cancel()
timers.clear()
timeoutFuture.foreach { _.cancel() }
currentState = nextState
- val stopEvent = StopEvent(reason, currentState.stateName, currentState.stateData)
+ val stopEvent: akka.actor.FSM.StopEvent[S, D] = StopEvent(reason, currentState.stateName, currentState.stateData)
if (terminateEvent.isDefinedAt(stopEvent))
terminateEvent(stopEvent)
}
@@ -771,7 +771,7 @@ trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒
private var full = false
private def advance() {
- val n = pos + 1
+ val n: Int = pos + 1
if (n == logDepth) {
full = true
pos = 0
@@ -782,7 +782,7 @@ trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒
private[akka] abstract override def processEvent(event: Event, source: AnyRef): Unit = {
if (debugEvent) {
- val srcstr = source match {
+ val srcstr: String = source match {
case s: String ⇒ s
case Timer(name, _, _, _, _) ⇒ "timer " + name
case a: ActorRef ⇒ a.toString
@@ -797,9 +797,9 @@ trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒
advance()
}
- val oldState = stateName
+ val oldState: S = stateName
super.processEvent(event, source)
- val newState = stateName
+ val newState: S = stateName
if (debugEvent && oldState != newState)
log.debug("transition " + oldState + " -> " + newState)
@@ -811,7 +811,7 @@ trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒
* The log entries are lost when this actor is restarted.
*/
protected def getLog: IndexedSeq[LogEntry[S, D]] = {
- val log = events zip states filter (_._1 ne null) map (x ⇒ LogEntry(x._2.asInstanceOf[S], x._1.stateData, x._1.event))
+ val log: Array[akka.actor.FSM.LogEntry[S, D]] = events zip states filter (_._1 ne null) map (x ⇒ LogEntry(x._2.asInstanceOf[S], x._1.stateData, x._1.event))
if (full) {
IndexedSeq() ++ log.drop(pos) ++ log.take(pos)
} else {
diff --git a/akka-actor/src/main/scala/akka/actor/FaultHandling.scala b/akka-actor/src/main/scala/akka/actor/FaultHandling.scala
index 075d7b0..f1f7a36 100644
--- a/akka-actor/src/main/scala/akka/actor/FaultHandling.scala
+++ b/akka-actor/src/main/scala/akka/actor/FaultHandling.scala
@@ -50,14 +50,14 @@ final case class ChildRestartStats(child: ActorRef, var maxNrOfRetriesCount: Int
* after a restart and if enough restarts happen during this time, it
* denies. Otherwise window closes and the scheme starts over.
*/
- val retriesDone = maxNrOfRetriesCount + 1
- val now = System.nanoTime
- val windowStart =
+ val retriesDone: Int = maxNrOfRetriesCount + 1
+ val now: Long = System.nanoTime
+ val windowStart: Long =
if (restartTimeWindowStartNanos == 0) {
restartTimeWindowStartNanos = now
now
} else restartTimeWindowStartNanos
- val insideWindow = (now - windowStart) <= TimeUnit.MILLISECONDS.toNanos(window)
+ val insideWindow: Boolean = (now - windowStart) <= TimeUnit.MILLISECONDS.toNanos(window)
if (insideWindow) {
maxNrOfRetriesCount = retriesDone
retriesDone <= retries
@@ -124,25 +124,25 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits {
/**
* Java API: Returning this directive resumes message processing for the failed Actor
*/
- def resume = Resume
+ def resume: akka.actor.SupervisorStrategy.Resume.type = Resume
/**
* Java API: Returning this directive discards the old Actor instance and replaces it with a new,
* then resumes message processing.
*/
- def restart = Restart
+ def restart: akka.actor.SupervisorStrategy.Restart.type = Restart
/**
* Java API: Returning this directive stops the Actor
*/
- def stop = Stop
+ def stop: akka.actor.SupervisorStrategy.Stop.type = Stop
/**
* Java API: Returning this directive escalates the failure to the supervisor of the supervisor,
* by rethrowing the cause of the failure, i.e. the supervisor fails with
* the same exception as the child.
*/
- def escalate = Escalate
+ def escalate: akka.actor.SupervisorStrategy.Escalate.type = Escalate
/**
* When supervisorStrategy is not specified for an actor this
@@ -210,7 +210,7 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits {
* Throwable hierarchy.
*/
def makeDecider(flat: Iterable[CauseDirective]): Decider = {
- val directives = sort(flat)
+ val directives: scala.collection.immutable.Seq[akka.actor.SupervisorStrategy.CauseDirective] = sort(flat)
{ case x ⇒ directives collectFirst { case (c, d) if c isInstance x ⇒ d } getOrElse Escalate }
}
@@ -293,7 +293,7 @@ abstract class SupervisorStrategy {
* @param children is a lazy collection (a view)
*/
def handleFailure(context: ActorContext, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Boolean = {
- val directive = decider.applyOrElse(cause, escalateDefault)
+ val directive: akka.actor.SupervisorStrategy.Directive = decider.applyOrElse(cause, escalateDefault)
directive match {
case Resume ⇒
logFailure(context, child, cause, directive)
@@ -328,7 +328,7 @@ abstract class SupervisorStrategy {
*/
def logFailure(context: ActorContext, child: ActorRef, cause: Throwable, decision: Directive): Unit =
if (loggingEnabled) {
- val logMessage = cause match {
+ val logMessage: String = cause match {
case e: ActorInitializationException if e.getCause ne null ⇒ e.getCause match {
case ex: InvocationTargetException if ex.getCause ne null ⇒ ex.getCause.getMessage
case ex ⇒ ex.getMessage
@@ -364,7 +364,7 @@ abstract class SupervisorStrategy {
* therefore not prepared to be resumed without prior suspend.
*/
final def restartChild(child: ActorRef, cause: Throwable, suspendFirst: Boolean): Unit = {
- val c = child.asInstanceOf[InternalActorRef]
+ val c: akka.actor.InternalActorRef = child.asInstanceOf[InternalActorRef]
if (suspendFirst) c.suspend()
c.restart(cause)
}
diff --git a/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala b/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala
index 88b3968..c2ea167 100644
--- a/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala
+++ b/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala
@@ -36,9 +36,9 @@ trait IndirectActorProducer {
}
private[akka] object IndirectActorProducer {
- val CreatorFunctionConsumerClass = classOf[CreatorFunctionConsumer]
- val CreatorConsumerClass = classOf[CreatorConsumer]
- val TypedCreatorFunctionConsumerClass = classOf[TypedCreatorFunctionConsumer]
+ val CreatorFunctionConsumerClass: Class[akka.actor.CreatorFunctionConsumer] = classOf[CreatorFunctionConsumer]
+ val CreatorConsumerClass: Class[akka.actor.CreatorConsumer] = classOf[CreatorConsumer]
+ val TypedCreatorFunctionConsumerClass: Class[akka.actor.TypedCreatorFunctionConsumer] = classOf[TypedCreatorFunctionConsumer]
def apply(clazz: Class[_], args: immutable.Seq[Any]): IndirectActorProducer = {
if (classOf[IndirectActorProducer].isAssignableFrom(clazz)) {
@@ -67,24 +67,24 @@ private[akka] object IndirectActorProducer {
* INTERNAL API
*/
private[akka] class CreatorFunctionConsumer(creator: () ⇒ Actor) extends IndirectActorProducer {
- override def actorClass = classOf[Actor]
- override def produce() = creator()
+ override def actorClass: Class[akka.actor.Actor] = classOf[Actor]
+ override def produce(): akka.actor.Actor = creator()
}
/**
* INTERNAL API
*/
private[akka] class CreatorConsumer(clazz: Class[_ <: Actor], creator: Creator[Actor]) extends IndirectActorProducer {
- override def actorClass = clazz
- override def produce() = creator.create()
+ override def actorClass: Class[_ <: akka.actor.Actor] = clazz
+ override def produce(): akka.actor.Actor = creator.create()
}
/**
* INTERNAL API
*/
private[akka] class TypedCreatorFunctionConsumer(clz: Class[_ <: Actor], creator: () ⇒ Actor) extends IndirectActorProducer {
- override def actorClass = clz
- override def produce() = creator()
+ override def actorClass: Class[_ <: akka.actor.Actor] = clz
+ override def produce(): akka.actor.Actor = creator()
}
/**
@@ -92,8 +92,8 @@ private[akka] class TypedCreatorFunctionConsumer(clz: Class[_ <: Actor], creator
*/
private[akka] class ArgsReflectConstructor(clz: Class[_ <: Actor], args: immutable.Seq[Any]) extends IndirectActorProducer {
private[this] val constructor = Reflect.findConstructor(clz, args)
- override def actorClass = clz
- override def produce() = Reflect.instantiate(constructor, args).asInstanceOf[Actor]
+ override def actorClass: Class[_ <: akka.actor.Actor] = clz
+ override def produce(): akka.actor.Actor = Reflect.instantiate(constructor, args).asInstanceOf[Actor]
}
/**
@@ -101,6 +101,6 @@ private[akka] class ArgsReflectConstructor(clz: Class[_ <: Actor], args: immutab
*/
private[akka] class NoArgsReflectConstructor(clz: Class[_ <: Actor]) extends IndirectActorProducer {
Reflect.findConstructor(clz, List.empty)
- override def actorClass = clz
- override def produce() = Reflect.instantiate(clz)
+ override def actorClass: Class[_ <: akka.actor.Actor] = clz
+ override def produce(): akka.actor.Actor = Reflect.instantiate(clz)
}
diff --git a/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala b/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala
index 8357971..dde42f5 100644
--- a/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala
+++ b/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala
@@ -43,20 +43,20 @@ class LightArrayRevolverScheduler(
import Helpers.Requiring
import Helpers.ConfigOps
- val WheelSize =
+ val WheelSize: Int =
config.getInt("akka.scheduler.ticks-per-wheel")
.requiring(ticks ⇒ (ticks & (ticks - 1)) == 0, "ticks-per-wheel must be a power of 2")
- val TickDuration =
+ val TickDuration: scala.concurrent.duration.FiniteDuration =
config.getMillisDuration("akka.scheduler.tick-duration")
.requiring(_ >= 10.millis || !Helpers.isWindows, "minimum supported akka.scheduler.tick-duration on Windows is 10ms")
.requiring(_ >= 1.millis, "minimum supported akka.scheduler.tick-duration is 1ms")
- val ShutdownTimeout = config.getMillisDuration("akka.scheduler.shutdown-timeout")
+ val ShutdownTimeout: scala.concurrent.duration.FiniteDuration = config.getMillisDuration("akka.scheduler.shutdown-timeout")
import LightArrayRevolverScheduler._
private def roundUp(d: FiniteDuration): FiniteDuration = {
- val dn = d.toNanos
- val r = ((dn - 1) / tickNanos + 1) * tickNanos
+ val dn: Long = d.toNanos
+ val r: Long = ((dn - 1) / tickNanos + 1) * tickNanos
if (r != dn && r > 0 && dn > 0) r.nanos else d
}
@@ -81,7 +81,7 @@ class LightArrayRevolverScheduler(
*/
protected def waitNanos(nanos: Long): Unit = {
// see http://www.javamex.com/tutorials/threads/sleep_issues.shtml
- val sleepMs = if (Helpers.isWindows) (nanos + 4999999) / 10000000 * 10 else (nanos + 999999) / 1000000
+ val sleepMs: Long = if (Helpers.isWindows) (nanos + 4999999) / 10000000 * 10 else (nanos + 999999) / 1000000
try Thread.sleep(sleepMs) catch {
case _: InterruptedException ⇒ Thread.currentThread.interrupt() // we got woken up
}
@@ -99,7 +99,7 @@ class LightArrayRevolverScheduler(
override def run(): Unit = {
try {
runnable.run()
- val driftNanos = clock() - getAndAdd(delay.toNanos)
+ val driftNanos: Long = clock() - getAndAdd(delay.toNanos)
if (self.get != null)
swap(schedule(executor, this, Duration.fromNanos(Math.max(delay.toNanos - driftNanos, 1))))
} catch {
@@ -164,11 +164,11 @@ class LightArrayRevolverScheduler(
} else if (stopped.get != null) {
throw new SchedulerException("cannot enqueue after timer shutdown")
} else {
- val delayNanos = delay.toNanos
+ val delayNanos: Long = delay.toNanos
checkMaxDelay(delayNanos)
- val ticks = (delayNanos / tickNanos).toInt
- val task = new TaskHolder(r, ticks, ec)
+ val ticks: Int = (delayNanos / tickNanos).toInt
+ val task: akka.actor.LightArrayRevolverScheduler.TaskHolder = new TaskHolder(r, ticks, ec)
queue.add(task)
if (stopped.get != null && task.cancel())
throw new SchedulerException("cannot enqueue after timer shutdown")
@@ -183,7 +183,7 @@ class LightArrayRevolverScheduler(
private val stopped = new AtomicReference[Promise[immutable.Seq[TimerTask]]]
private def stop(): Future[immutable.Seq[TimerTask]] = {
- val p = Promise[immutable.Seq[TimerTask]]()
+ val p: scala.concurrent.Promise[scala.collection.immutable.Seq[akka.actor.LightArrayRevolverScheduler.TimerTask]] = Promise[immutable.Seq[TimerTask]]()
if (stopped.compareAndSet(null, p)) {
// Interrupting the timer thread to make it shut down faster is not good since
// it could be in the middle of executing the scheduled tasks, which might not
@@ -195,9 +195,9 @@ class LightArrayRevolverScheduler(
@volatile private var timerThread: Thread = threadFactory.newThread(new Runnable {
- var tick = startTick
+ var tick: Int = startTick
var totalTick: Long = tick // tick count that doesn't wrap around, used for calculating sleep time
- val wheel = Array.fill(WheelSize)(new TaskQueue)
+ val wheel: Array[akka.actor.LightArrayRevolverScheduler.TaskQueue] = Array.fill(WheelSize)(new TaskQueue)
private def clearAll(): immutable.Seq[TimerTask] = {
@tailrec def collect(q: TaskQueue, acc: Vector[TimerTask]): Vector[TimerTask] = {
@@ -216,29 +216,29 @@ class LightArrayRevolverScheduler(
node.value.ticks match {
case 0 ⇒ node.value.executeTask()
case ticks ⇒
- val futureTick = ((
+ val futureTick: Int = ((
time - start + // calculate the nanos since timer start
(ticks * tickNanos) + // adding the desired delay
tickNanos - 1 // rounding up
) / tickNanos).toInt // and converting to slot number
// tick is an Int that will wrap around, but toInt of futureTick gives us modulo operations
// and the difference (offset) will be correct in any case
- val offset = futureTick - tick
- val bucket = futureTick & wheelMask
+ val offset: Int = futureTick - tick
+ val bucket: Int = futureTick & wheelMask
node.value.ticks = offset
wheel(bucket).addNode(node)
}
checkQueue(time)
}
- override final def run =
+ override final def run: Unit =
try nextTick()
catch {
case t: Throwable ⇒
log.error(t, "exception on LARS’ timer thread")
stopped.get match {
case null ⇒
- val thread = threadFactory.newThread(this)
+ val thread: Thread = threadFactory.newThread(this)
log.info("starting new LARS thread")
try thread.start()
catch {
@@ -256,22 +256,22 @@ class LightArrayRevolverScheduler(
}
@tailrec final def nextTick(): Unit = {
- val time = clock()
- val sleepTime = start + (totalTick * tickNanos) - time
+ val time: Long = clock()
+ val sleepTime: Long = start + (totalTick * tickNanos) - time
if (sleepTime > 0) {
// check the queue before taking a nap
checkQueue(time)
waitNanos(sleepTime)
} else {
- val bucket = tick & wheelMask
- val tasks = wheel(bucket)
- val putBack = new TaskQueue
+ val bucket: Int = tick & wheelMask
+ val tasks: akka.actor.LightArrayRevolverScheduler.TaskQueue = wheel(bucket)
+ val putBack: akka.actor.LightArrayRevolverScheduler.TaskQueue = new TaskQueue
@tailrec def executeBucket(): Unit = tasks.pollNode() match {
case null ⇒ ()
case node ⇒
- val task = node.value
+ val task: akka.actor.LightArrayRevolverScheduler.TaskHolder = node.value
if (!task.isCancelled) {
if (task.ticks >= WheelSize) {
task.ticks -= WheelSize
diff --git a/akka-actor/src/main/scala/akka/actor/Props.scala b/akka-actor/src/main/scala/akka/actor/Props.scala
index 65d1cc2..e187f31 100644
--- a/akka-actor/src/main/scala/akka/actor/Props.scala
+++ b/akka-actor/src/main/scala/akka/actor/Props.scala
@@ -34,17 +34,17 @@ object Props extends AbstractProps {
/**
* The default Deploy instance which is used when creating a Props
*/
- final val defaultDeploy = Deploy()
+ final val defaultDeploy: akka.actor.Deploy = Deploy()
/**
* A Props instance whose creator will create an actor that doesn't respond to any message
*/
- final val empty = Props[EmptyActor]
+ final val empty: akka.actor.Props = Props[EmptyActor]
/**
* The default Props instance, uses the settings from the Props object starting with default*.
*/
- final val default = Props(defaultDeploy, classOf[CreatorFunctionConsumer], List(defaultCreator))
+ final val default: akka.actor.Props = Props(defaultDeploy, classOf[CreatorFunctionConsumer], List(defaultCreator))
/**
* INTERNAL API
@@ -52,7 +52,7 @@ object Props extends AbstractProps {
* (Not because it is so immensely complicated, only because we might remove it if no longer needed internally)
*/
private[akka] class EmptyActor extends Actor {
- def receive = Actor.emptyBehavior
+ def receive: akka.actor.Actor.emptyBehavior.type = Actor.emptyBehavior
}
/**
diff --git a/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala b/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala
index fe6bc0f..776cda6 100644
--- a/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala
+++ b/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala
@@ -18,19 +18,19 @@ class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAcces
override def getClassFor[T: ClassTag](fqcn: String): Try[Class[_ <: T]] =
Try[Class[_ <: T]]({
- val c = Class.forName(fqcn, false, classLoader).asInstanceOf[Class[_ <: T]]
- val t = implicitly[ClassTag[T]].runtimeClass
+ val c: Class[_ <: T] = Class.forName(fqcn, false, classLoader).asInstanceOf[Class[_ <: T]]
+ val t: Class[_] = implicitly[ClassTag[T]].runtimeClass
if (t.isAssignableFrom(c)) c else throw new ClassCastException(t + " is not assignable from " + c)
})
override def createInstanceFor[T: ClassTag](clazz: Class[_], args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
Try {
- val types = args.map(_._1).toArray
- val values = args.map(_._2).toArray
- val constructor = clazz.getDeclaredConstructor(types: _*)
+ val types: Array[Class[_]] = args.map(_._1).toArray
+ val values: Array[AnyRef] = args.map(_._2).toArray
+ val constructor: java.lang.reflect.Constructor[_] = clazz.getDeclaredConstructor(types: _*)
constructor.setAccessible(true)
- val obj = constructor.newInstance(values: _*)
- val t = implicitly[ClassTag[T]].runtimeClass
+ val obj: Any = constructor.newInstance(values: _*)
+ val t: Class[_] = implicitly[ClassTag[T]].runtimeClass
if (t.isInstance(obj)) obj.asInstanceOf[T] else throw new ClassCastException(clazz.getName + " is not a subtype of " + t)
} recover { case i: InvocationTargetException if i.getTargetException ne null ⇒ throw i.getTargetException }
@@ -38,14 +38,14 @@ class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAcces
getClassFor(fqcn) flatMap { c ⇒ createInstanceFor(c, args) }
override def getObjectFor[T: ClassTag](fqcn: String): Try[T] = {
- val classTry =
+ val classTry: scala.util.Try[Class[_ <: T]] =
if (fqcn.endsWith("$")) getClassFor(fqcn)
else getClassFor(fqcn + "$") recoverWith { case _ ⇒ getClassFor(fqcn) }
classTry flatMap { c ⇒
Try {
- val module = c.getDeclaredField("MODULE$")
+ val module: java.lang.reflect.Field = c.getDeclaredField("MODULE$")
module.setAccessible(true)
- val t = implicitly[ClassTag[T]].runtimeClass
+ val t: Class[_] = implicitly[ClassTag[T]].runtimeClass
module.get(null) match {
case null ⇒ throw new NullPointerException
case x if !t.isInstance(x) ⇒ throw new ClassCastException(fqcn + " is not a subtype of " + t)
diff --git a/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala b/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala
index 8ab2fb9..d32bc87 100644
--- a/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala
+++ b/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala
@@ -48,15 +48,15 @@ private[akka] class RepointableActorRef(
@volatile private var _lookupDoNotCallMeDirectly: Cell = _
def underlying: Cell = Unsafe.instance.getObjectVolatile(this, cellOffset).asInstanceOf[Cell]
- def lookup = Unsafe.instance.getObjectVolatile(this, lookupOffset).asInstanceOf[Cell]
+ def lookup: akka.actor.Cell = Unsafe.instance.getObjectVolatile(this, lookupOffset).asInstanceOf[Cell]
@tailrec final def swapCell(next: Cell): Cell = {
- val old = underlying
+ val old: akka.actor.Cell = underlying
if (Unsafe.instance.compareAndSwapObject(this, cellOffset, old, next)) old else swapCell(next)
}
@tailrec final def swapLookup(next: Cell): Cell = {
- val old = lookup
+ val old: akka.actor.Cell = lookup
if (Unsafe.instance.compareAndSwapObject(this, lookupOffset, old, next)) old else swapLookup(next)
}
@@ -89,11 +89,11 @@ private[akka] class RepointableActorRef(
def point(catchFailures: Boolean): this.type =
underlying match {
case u: UnstartedCell ⇒
- val cell =
+ val cell: akka.actor.Cell =
try newCell(u)
catch {
case NonFatal(ex) if catchFailures ⇒
- val safeDispatcher = system.dispatchers.defaultGlobalDispatcher
+ val safeDispatcher: akka.dispatch.MessageDispatcher = system.dispatchers.defaultGlobalDispatcher
new ActorCell(system, this, props, safeDispatcher, supervisor).initWithFailure(ex)
}
/*
@@ -168,9 +168,9 @@ private[akka] class RepointableActorRef(
def children: immutable.Iterable[ActorRef] = lookup.childrenRefs.children
- def !(message: Any)(implicit sender: ActorRef = Actor.noSender) = underlying.sendMessage(message, sender)
+ def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = underlying.sendMessage(message, sender)
- def sendSystemMessage(message: SystemMessage) = underlying.sendSystemMessage(message)
+ def sendSystemMessage(message: SystemMessage): Unit = underlying.sendSystemMessage(message)
@throws(classOf[java.io.ObjectStreamException])
protected def writeReplace(): AnyRef = SerializedActorRef(this)
@@ -204,7 +204,7 @@ private[akka] class UnstartedCell(
var sysQ = sysmsgQueue.reverse
sysmsgQueue = SystemMessageList.LNil
while (sysQ.nonEmpty) {
- val msg = sysQ.head
+ val msg: akka.dispatch.sysmsg.SystemMessage = sysQ.head
sysQ = sysQ.tail
msg.unlink()
cell.sendSystemMessage(msg)
@@ -231,7 +231,7 @@ private[akka] class UnstartedCell(
def restart(cause: Throwable): Unit = sendSystemMessage(Recreate(cause))
def stop(): Unit = sendSystemMessage(Terminate())
override private[akka] def isTerminated: Boolean = locked {
- val cell = self.underlying
+ val cell: akka.actor.Cell = self.underlying
if (cellIsReady(cell)) cell.isTerminated else false
}
def parent: InternalActorRef = supervisor
@@ -242,7 +242,7 @@ private[akka] class UnstartedCell(
def sendMessage(msg: Envelope): Unit = {
if (lock.tryLock(timeout.length, timeout.unit)) {
try {
- val cell = self.underlying
+ val cell: akka.actor.Cell = self.underlying
if (cellIsReady(cell)) {
cell.sendMessage(msg)
} else if (!queue.offer(msg)) {
@@ -259,7 +259,7 @@ private[akka] class UnstartedCell(
def sendSystemMessage(msg: SystemMessage): Unit = {
lock.lock // we cannot lose system messages, ever, and we cannot throw an Error from here as well
try {
- val cell = self.underlying
+ val cell: akka.actor.Cell = self.underlying
if (cellIsReady(cell))
cell.sendSystemMessage(msg)
else {
@@ -274,12 +274,12 @@ private[akka] class UnstartedCell(
private[this] final def cellIsReady(cell: Cell): Boolean = (cell ne this) && (cell ne null)
def hasMessages: Boolean = locked {
- val cell = self.underlying
+ val cell: akka.actor.Cell = self.underlying
if (cellIsReady(cell)) cell.hasMessages else !queue.isEmpty
}
def numberOfMessages: Int = locked {
- val cell = self.underlying
+ val cell: akka.actor.Cell = self.underlying
if (cellIsReady(cell)) cell.numberOfMessages else queue.size
}
diff --git a/akka-actor/src/main/scala/akka/actor/Scheduler.scala b/akka-actor/src/main/scala/akka/actor/Scheduler.scala
index 3a70f9f..5621817 100644
--- a/akka-actor/src/main/scala/akka/actor/Scheduler.scala
+++ b/akka-actor/src/main/scala/akka/actor/Scheduler.scala
@@ -53,7 +53,7 @@ trait Scheduler {
executor: ExecutionContext,
sender: ActorRef = Actor.noSender): Cancellable =
schedule(initialDelay, interval, new Runnable {
- def run = {
+ def run: Unit = {
receiver ! message
if (receiver.isTerminated)
throw new SchedulerException("timer active for terminated actor")
@@ -80,7 +80,7 @@ trait Scheduler {
interval: FiniteDuration)(f: ⇒ Unit)(
implicit
executor: ExecutionContext): Cancellable =
- schedule(initialDelay, interval, new Runnable { override def run = f })
+ schedule(initialDelay, interval, new Runnable { override def run: Unit = f })
/**
* Schedules a `Runnable` to be run repeatedly with an initial delay and
@@ -122,7 +122,7 @@ trait Scheduler {
executor: ExecutionContext,
sender: ActorRef = Actor.noSender): Cancellable =
scheduleOnce(delay, new Runnable {
- override def run = receiver ! message
+ override def run: Unit = receiver ! message
})
/**
@@ -137,7 +137,7 @@ trait Scheduler {
final def scheduleOnce(delay: FiniteDuration)(f: ⇒ Unit)(
implicit
executor: ExecutionContext): Cancellable =
- scheduleOnce(delay, new Runnable { override def run = f })
+ scheduleOnce(delay, new Runnable { override def run: Unit = f })
/**
* Schedules a Runnable to be run once with a delay, i.e. a time period that
diff --git a/akka-actor/src/main/scala/akka/actor/Stash.scala b/akka-actor/src/main/scala/akka/actor/Stash.scala
index 8f7f50c..ee3586c 100644
--- a/akka-actor/src/main/scala/akka/actor/Stash.scala
+++ b/akka-actor/src/main/scala/akka/actor/Stash.scala
@@ -154,7 +154,7 @@ private[akka] trait StashSupport {
* @throws IllegalStateException if the same message is stashed more than once
*/
def stash(): Unit = {
- val currMsg = actorCell.currentMessage
+ val currMsg: akka.dispatch.Envelope = actorCell.currentMessage
if (theStash.nonEmpty && (currMsg eq theStash.last))
throw new IllegalStateException(s"Can't stash the same message $currMsg more than once")
if (capacity <= 0 || theStash.size < capacity) theStash :+= currMsg
@@ -214,7 +214,7 @@ private[akka] trait StashSupport {
*/
private[akka] def unstashAll(filterPredicate: Any ⇒ Boolean): Unit = {
try {
- val i = theStash.reverseIterator.filter(envelope ⇒ filterPredicate(envelope.message))
+ val i: Iterator[akka.dispatch.Envelope] = theStash.reverseIterator.filter(envelope ⇒ filterPredicate(envelope.message))
while (i.hasNext) enqueueFirst(i.next())
} finally {
theStash = Vector.empty[Envelope]
@@ -227,7 +227,7 @@ private[akka] trait StashSupport {
* Clears the stash and and returns all envelopes that have not been unstashed.
*/
private[akka] def clearStash(): Vector[Envelope] = {
- val stashed = theStash
+ val stashed: scala.collection.immutable.Vector[akka.dispatch.Envelope] = theStash
theStash = Vector.empty[Envelope]
stashed
}
diff --git a/akka-actor/src/main/scala/akka/actor/TypedActor.scala b/akka-actor/src/main/scala/akka/actor/TypedActor.scala
index 5c9e462..768a969 100644
--- a/akka-actor/src/main/scala/akka/actor/TypedActor.scala
+++ b/akka-actor/src/main/scala/akka/actor/TypedActor.scala
@@ -70,10 +70,10 @@ trait TypedActorFactory {
* Creates a new TypedActor with the specified properties
*/
def typedActorOf[R <: AnyRef, T <: R](props: TypedProps[T]): R = {
- val proxyVar = new AtomVar[R] //Chicken'n'egg-resolver
- val c = props.creator //Cache this to avoid closing over the Props
- val i = props.interfaces //Cache this to avoid closing over the Props
- val ap = Props(new TypedActor.TypedActor[R, T](proxyVar, c(), i)).withDeploy(props.actorProps.deploy)
+ val proxyVar: java.util.concurrent.atomic.AtomicReference[R] = new AtomVar[R] //Chicken'n'egg-resolver
+ val c: () ⇒ T = props.creator //Cache this to avoid closing over the Props
+ val i: scala.collection.immutable.Seq[Class[_]] = props.interfaces //Cache this to avoid closing over the Props
+ val ap: akka.actor.Props = Props(new TypedActor.TypedActor[R, T](proxyVar, c(), i)).withDeploy(props.actorProps.deploy)
typedActor.createActorRefProxy(props, proxyVar, actorFactory.actorOf(ap))
}
@@ -81,10 +81,10 @@ trait TypedActorFactory {
* Creates a new TypedActor with the specified properties
*/
def typedActorOf[R <: AnyRef, T <: R](props: TypedProps[T], name: String): R = {
- val proxyVar = new AtomVar[R] //Chicken'n'egg-resolver
- val c = props.creator //Cache this to avoid closing over the Props
- val i = props.interfaces //Cache this to avoid closing over the Props
- val ap = Props(new akka.actor.TypedActor.TypedActor[R, T](proxyVar, c(), i)).withDeploy(props.actorProps.deploy)
+ val proxyVar: java.util.concurrent.atomic.AtomicReference[R] = new AtomVar[R] //Chicken'n'egg-resolver
+ val c: () ⇒ T = props.creator //Cache this to avoid closing over the Props
+ val i: scala.collection.immutable.Seq[Class[_]] = props.interfaces //Cache this to avoid closing over the Props
+ val ap: akka.actor.Props = Props(new akka.actor.TypedActor.TypedActor[R, T](proxyVar, c(), i)).withDeploy(props.actorProps.deploy)
typedActor.createActorRefProxy(props, proxyVar, actorFactory.actorOf(ap, name))
}
@@ -103,7 +103,7 @@ trait TypedActorFactory {
object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvider {
override def get(system: ActorSystem): TypedActorExtension = super.get(system)
- def lookup() = this
+ def lookup(): akka.actor.TypedActor.type = this
def createExtension(system: ExtendedActorSystem): TypedActorExtension = new TypedActorExtension(system)
/**
@@ -128,10 +128,10 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
*/
final case class MethodCall(method: Method, parameters: Array[AnyRef]) {
- def isOneWay = method.getReturnType == java.lang.Void.TYPE
- def returnsFuture = classOf[Future[_]] isAssignableFrom method.getReturnType
- def returnsJOption = classOf[akka.japi.Option[_]] isAssignableFrom method.getReturnType
- def returnsOption = classOf[scala.Option[_]] isAssignableFrom method.getReturnType
+ def isOneWay: Boolean = method.getReturnType == java.lang.Void.TYPE
+ def returnsFuture: Boolean = classOf[Future[_]] isAssignableFrom method.getReturnType
+ def returnsJOption: Boolean = classOf[akka.japi.Option[_]] isAssignableFrom method.getReturnType
+ def returnsOption: Boolean = classOf[scala.Option[_]] isAssignableFrom method.getReturnType
/**
* Invokes the Method on the supplied instance
@@ -150,12 +150,12 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
case null ⇒ SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, null)
case ps if ps.length == 0 ⇒ SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, Array())
case ps ⇒
- val serialization = SerializationExtension(akka.serialization.JavaSerializer.currentSystem.value)
- val serializedParameters = new Array[(Int, Class[_], Array[Byte])](ps.length)
+ val serialization: akka.serialization.Serialization = SerializationExtension(akka.serialization.JavaSerializer.currentSystem.value)
+ val serializedParameters: Array[(Int, Class[_], Array[Byte])] = new Array[(Int, Class[_], Array[Byte])](ps.length)
for (i ← 0 until ps.length) {
- val p = ps(i)
- val s = serialization.findSerializerFor(p)
- val m = if (s.includeManifest) p.getClass else null
+ val p: AnyRef = ps(i)
+ val s: akka.serialization.Serializer = serialization.findSerializerFor(p)
+ val m: Class[_ <: AnyRef] = if (s.includeManifest) p.getClass else null
serializedParameters(i) = (s.identifier, m, s toBinary parameters(i)) //Mutable for the sake of sanity
}
@@ -173,11 +173,11 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
//TODO implement writeObject and readObject to serialize
//TODO Possible optimization is to special encode the parameter-types to conserve space
@throws(classOf[ObjectStreamException]) private def readResolve(): AnyRef = {
- val system = akka.serialization.JavaSerializer.currentSystem.value
+ val system: akka.actor.ExtendedActorSystem = akka.serialization.JavaSerializer.currentSystem.value
if (system eq null) throw new IllegalStateException(
"Trying to deserialize a SerializedMethodCall without an ActorSystem in scope." +
" Use akka.serialization.Serialization.currentSystem.withValue(system) { ... }")
- val serialization = SerializationExtension(system)
+ val serialization: akka.serialization.Serialization = SerializationExtension(system)
MethodCall(ownerType.getDeclaredMethod(methodName, parameterTypes: _*), serializedParameters match {
case null ⇒ null
case a if a.length == 0 ⇒ Array[AnyRef]()
@@ -235,7 +235,7 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
/**
* Returns the default dispatcher (for a TypedActor) when inside a method call in a TypedActor.
*/
- implicit def dispatcher = context.dispatcher
+ implicit def dispatcher: scala.concurrent.ExecutionContextExecutor = context.dispatcher
/**
* INTERNAL API
@@ -301,15 +301,15 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
}
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case m: MethodCall ⇒ withContext {
if (m.isOneWay) m(me)
else {
try {
- val s = sender()
+ val s: akka.actor.ActorRef = sender()
m(me) match {
case f: Future[_] if m.returnsFuture ⇒
- implicit val dispatcher = context.dispatcher
+ implicit val dispatcher: scala.concurrent.ExecutionContextExecutor = context.dispatcher
f onComplete {
case Success(null) ⇒ s ! NullResponse
case Success(result) ⇒ s ! result
@@ -405,14 +405,14 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
*/
private[akka] class TypedActorInvocationHandler(@transient val extension: TypedActorExtension, @transient val actorVar: AtomVar[ActorRef], @transient val timeout: Timeout) extends InvocationHandler with Serializable {
- def actor = actorVar.get
+ def actor: akka.actor.ActorRef = actorVar.get
@throws(classOf[Throwable])
def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]): AnyRef = method.getName match {
case "toString" ⇒ actor.toString
case "equals" ⇒ (args.length == 1 && (proxy eq args(0)) || actor == extension.getActorRefFor(args(0))).asInstanceOf[AnyRef] //Force boxing of the boolean
case "hashCode" ⇒ actor.hashCode.asInstanceOf[AnyRef]
case _ ⇒
- implicit val dispatcher = extension.system.dispatcher
+ implicit val dispatcher: scala.concurrent.ExecutionContextExecutor = extension.system.dispatcher
import akka.pattern.ask
MethodCall(method, args) match {
case m if m.isOneWay ⇒
@@ -422,7 +422,7 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
case other ⇒ other
}
case m if m.returnsJOption || m.returnsOption ⇒
- val f = ask(actor, m)(timeout)
+ val f: scala.concurrent.Future[Any] = ask(actor, m)(timeout)
(try { Await.ready(f, timeout.duration).value } catch { case _: TimeoutException ⇒ None }) match {
case None | Some(Success(NullResponse)) | Some(Failure(_: AskTimeoutException)) ⇒
if (m.returnsJOption) JOption.none[Any] else None
@@ -636,7 +636,7 @@ final case class ContextualTypedActorFactory(typedActor: TypedActorExtension, ac
class TypedActorExtension(val system: ExtendedActorSystem) extends TypedActorFactory with Extension {
import TypedActor._ //Import the goodies from the companion object
protected def actorFactory: ActorRefFactory = system
- protected def typedActor = this
+ protected def typedActor: akka.actor.TypedActorExtension = this
import system.settings
import akka.util.Helpers.ConfigOps
@@ -644,7 +644,7 @@ class TypedActorExtension(val system: ExtendedActorSystem) extends TypedActorFac
/**
* Default timeout for typed actor methods with non-void return type
*/
- final val DefaultReturnTimeout = Timeout(settings.config.getMillisDuration("akka.actor.typed.timeout"))
+ final val DefaultReturnTimeout: akka.util.Timeout = Timeout(settings.config.getMillisDuration("akka.actor.typed.timeout"))
/**
* Retrieves the underlying ActorRef for the supplied TypedActor proxy, or null if none found
@@ -665,8 +665,8 @@ class TypedActorExtension(val system: ExtendedActorSystem) extends TypedActorFac
*/
private[akka] def createActorRefProxy[R <: AnyRef, T <: R](props: TypedProps[T], proxyVar: AtomVar[R], actorRef: ⇒ ActorRef): R = {
//Warning, do not change order of the following statements, it's some elaborate chicken-n-egg handling
- val actorVar = new AtomVar[ActorRef](null)
- val proxy = Proxy.newProxyInstance(
+ val actorVar: java.util.concurrent.atomic.AtomicReference[akka.actor.ActorRef] = new AtomVar[ActorRef](null)
+ val proxy: R = Proxy.newProxyInstance(
(props.loader orElse props.interfaces.collectFirst { case any ⇒ any.getClassLoader }).orNull, //If we have no loader, we arbitrarily take the loader of the first interface
props.interfaces.toArray,
new TypedActorInvocationHandler(this, actorVar, props.timeout getOrElse DefaultReturnTimeout)).asInstanceOf[R]
diff --git a/akka-actor/src/main/scala/akka/actor/UntypedActor.scala b/akka-actor/src/main/scala/akka/actor/UntypedActor.scala
index 4925561..c60465f 100644
--- a/akka-actor/src/main/scala/akka/actor/UntypedActor.scala
+++ b/akka-actor/src/main/scala/akka/actor/UntypedActor.scala
@@ -163,7 +163,7 @@ abstract class UntypedActor extends Actor {
@throws(classOf[Exception])
override def postRestart(reason: Throwable): Unit = super.postRestart(reason)
- final def receive = { case msg ⇒ onReceive(msg) }
+ final def receive: PartialFunction[Any, Unit] = { case msg ⇒ onReceive(msg) }
/**
* Recommended convention is to call this method if the message
diff --git a/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala b/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala
index d29bf9b..3e16535 100644
--- a/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala
+++ b/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala
@@ -42,46 +42,46 @@ trait Creators { this: ActorDSL.type ⇒
/**
* @see [[akka.actor.OneForOneStrategy]]
*/
- def OneForOneStrategy = akka.actor.OneForOneStrategy
+ def OneForOneStrategy: akka.actor.OneForOneStrategy.type = akka.actor.OneForOneStrategy
/**
* @see [[akka.actor.AllForOneStrategy]]
*/
- def AllForOneStrategy = akka.actor.AllForOneStrategy
+ def AllForOneStrategy: akka.actor.AllForOneStrategy.type = akka.actor.AllForOneStrategy
/**
* @see [[akka.actor.SupervisorStrategy]]
*/
- def Stop = SupervisorStrategy.Stop
+ def Stop: akka.actor.SupervisorStrategy.Stop.type = SupervisorStrategy.Stop
/**
* @see [[akka.actor.SupervisorStrategy]]
*/
- def Restart = SupervisorStrategy.Restart
+ def Restart: akka.actor.SupervisorStrategy.Restart.type = SupervisorStrategy.Restart
/**
* @see [[akka.actor.SupervisorStrategy]]
*/
- def Resume = SupervisorStrategy.Resume
+ def Resume: akka.actor.SupervisorStrategy.Resume.type = SupervisorStrategy.Resume
/**
* @see [[akka.actor.SupervisorStrategy]]
*/
- def Escalate = SupervisorStrategy.Escalate
+ def Escalate: akka.actor.SupervisorStrategy.Escalate.type = SupervisorStrategy.Escalate
/**
* Add the given behavior on top of the behavior stack for this actor. This
* stack is cleared upon restart. Use `unbecome()` to pop an element off
* this stack.
*/
- def becomeStacked(r: Receive) = context.become(r, discardOld = false)
+ def becomeStacked(r: Receive): Unit = context.become(r, discardOld = false)
/**
* Replace the behavior at the top of the behavior stack for this actor. The
* stack is cleared upon restart. Use `unbecome()` to pop an element off
* this stack or `becomeStacked()` to push a new element on top of it.
*/
- def become(r: Receive) = context.become(r, discardOld = true)
+ def become(r: Receive): Unit = context.become(r, discardOld = true)
/**
* Pop the active behavior from the behavior stack of this actor. This stack
@@ -153,8 +153,8 @@ trait Creators { this: ActorDSL.type ⇒
*/
def actor[T <: Actor: ClassTag](ctor: ⇒ T)(implicit factory: ActorRefFactory): ActorRef = {
// configure dispatcher/mailbox based on runtime class
- val classOfActor = implicitly[ClassTag[T]].runtimeClass
- val props = mkProps(classOfActor, () ⇒ ctor)
+ val classOfActor: Class[_] = implicitly[ClassTag[T]].runtimeClass
+ val props: akka.actor.Props = mkProps(classOfActor, () ⇒ ctor)
factory.actorOf(props)
}
@@ -172,8 +172,8 @@ trait Creators { this: ActorDSL.type ⇒
*/
def actor[T <: Actor: ClassTag](name: String)(ctor: ⇒ T)(implicit factory: ActorRefFactory): ActorRef = {
// configure dispatcher/mailbox based on runtime class
- val classOfActor = implicitly[ClassTag[T]].runtimeClass
- val props = mkProps(classOfActor, () ⇒ ctor)
+ val classOfActor: Class[_] = implicitly[ClassTag[T]].runtimeClass
+ val props: akka.actor.Props = mkProps(classOfActor, () ⇒ ctor)
if (name == null) factory.actorOf(props)
else factory.actorOf(props, name)
diff --git a/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala b/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala
index 0d0c5ff..910b3ad 100644
--- a/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala
+++ b/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala
@@ -32,10 +32,10 @@ private[akka] object Inbox {
def client: ActorRef
}
private final case class Get(deadline: Deadline, client: ActorRef = null) extends Query {
- def withClient(c: ActorRef) = copy(client = c)
+ def withClient(c: ActorRef): akka.actor.dsl.Inbox.Get = copy(client = c)
}
private final case class Select(deadline: Deadline, predicate: PartialFunction[Any, Any], client: ActorRef = null) extends Query {
- def withClient(c: ActorRef) = copy(client = c)
+ def withClient(c: ActorRef): akka.actor.dsl.Inbox.Select = copy(client = c)
}
private final case class StartWatch(target: ActorRef)
private case object Kick
@@ -47,10 +47,10 @@ trait Inbox { this: ActorDSL.type ⇒
import Inbox._
protected trait InboxExtension { this: Extension ⇒
- val DSLInboxQueueSize = config.getInt("inbox-size")
+ val DSLInboxQueueSize: Int = config.getInt("inbox-size")
- val inboxNr = new AtomicInteger
- val inboxProps = Props(classOf[InboxActor], ActorDSL, DSLInboxQueueSize)
+ val inboxNr: java.util.concurrent.atomic.AtomicInteger = new AtomicInteger
+ val inboxProps: akka.actor.Props = Props(classOf[InboxActor], ActorDSL, DSLInboxQueueSize)
def newReceiver: ActorRef = mkChild(inboxProps, "inbox-" + inboxNr.incrementAndGet)
}
@@ -60,13 +60,13 @@ trait Inbox { this: ActorDSL.type ⇒
}
private class InboxActor(size: Int) extends Actor with ActorLogging {
- var clients = Queue.empty[Query]
- val messages = Queue.empty[Any]
- var clientsByTimeout = TreeSet.empty[Query]
+ var clients: scala.collection.mutable.Queue[akka.actor.dsl.Inbox.Query] = Queue.empty[Query]
+ val messages: scala.collection.mutable.Queue[Any] = Queue.empty[Any]
+ var clientsByTimeout: scala.collection.immutable.TreeSet[akka.actor.dsl.Inbox.Query] = TreeSet.empty[Query]
var printedWarning = false
def enqueueQuery(q: Query) {
- val query = q withClient sender()
+ val query: akka.actor.dsl.Inbox.Query = q withClient sender()
clients enqueue query
clientsByTimeout += query
}
@@ -93,7 +93,7 @@ trait Inbox { this: ActorDSL.type ⇒
var currentDeadline: Option[(Deadline, Cancellable)] = None
- def receive = ({
+ def receive: PartialFunction[Any, Unit] = ({
case g: Get ⇒
if (messages.isEmpty) enqueueQuery(g)
else sender() ! messages.dequeue()
@@ -109,11 +109,11 @@ trait Inbox { this: ActorDSL.type ⇒
}
case StartWatch(target) ⇒ context watch target
case Kick ⇒
- val now = Deadline.now
- val pred = (q: Query) ⇒ q.deadline.time < now.time
- val overdue = clientsByTimeout.iterator.takeWhile(pred)
+ val now: scala.concurrent.duration.Deadline = Deadline.now
+ val pred: akka.actor.dsl.Inbox.Query ⇒ Boolean = (q: Query) ⇒ q.deadline.time < now.time
+ val overdue: Iterator[akka.actor.dsl.Inbox.Query] = clientsByTimeout.iterator.takeWhile(pred)
while (overdue.hasNext) {
- val toKick = overdue.next()
+ val toKick: akka.actor.dsl.Inbox.Query = overdue.next()
toKick.client ! Status.Failure(new TimeoutException("deadline passed"))
}
clients = clients.filterNot(pred)
@@ -135,7 +135,7 @@ trait Inbox { this: ActorDSL.type ⇒
currentDeadline = None
}
} else {
- val next = clientsByTimeout.head.deadline
+ val next: scala.concurrent.duration.Deadline = clientsByTimeout.head.deadline
import context.dispatcher
if (currentDeadline.isEmpty) {
currentDeadline = Some((next, context.system.scheduler.scheduleOnce(next.timeLeft, self, Kick)))
@@ -184,7 +184,7 @@ trait Inbox { this: ActorDSL.type ⇒
* this method within an actor!</b>
*/
def receive(timeout: FiniteDuration = defaultTimeout): Any = {
- implicit val t = Timeout(timeout + extraTime)
+ implicit val t: akka.util.Timeout = Timeout(timeout + extraTime)
Await.result(receiver ? Get(Deadline.now + timeout), Duration.Inf)
}
@@ -201,7 +201,7 @@ trait Inbox { this: ActorDSL.type ⇒
* this method within an actor!</b>
*/
def select[T](timeout: FiniteDuration = defaultTimeout)(predicate: PartialFunction[Any, T]): T = {
- implicit val t = Timeout(timeout + extraTime)
+ implicit val t: akka.util.Timeout = Timeout(timeout + extraTime)
predicate(Await.result(receiver ? Select(Deadline.now + timeout, predicate), Duration.Inf))
}
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala b/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala
index beed838..e179751 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala
@@ -14,7 +14,7 @@ import akka.serialization.SerializerWithStringManifest
import java.util.Optional
private[akka] object Children {
- val GetNobody = () ⇒ Nobody
+ val GetNobody: () ⇒ akka.actor.Nobody.type = () ⇒ Nobody
}
private[akka] trait Children { this: ActorCell ⇒
@@ -60,14 +60,14 @@ private[akka] trait Children { this: ActorCell ⇒
}
private[akka] def addFunctionRef(f: (ActorRef, Any) ⇒ Unit, name: String = ""): FunctionRef = {
- val r = randomName(new java.lang.StringBuilder("$$"))
- val n = if (name != "") s"$r-$name" else r
- val childPath = new ChildActorPath(self.path, n, ActorCell.newUid())
- val ref = new FunctionRef(childPath, provider, system.eventStream, f)
+ val r: String = randomName(new java.lang.StringBuilder("$$"))
+ val n: String = if (name != "") s"$r-$name" else r
+ val childPath: akka.actor.ChildActorPath = new ChildActorPath(self.path, n, ActorCell.newUid())
+ val ref: akka.actor.FunctionRef = new FunctionRef(childPath, provider, system.eventStream, f)
@tailrec def rec(): Unit = {
- val old = functionRefs
- val added = old.updated(childPath.name, ref)
+ val old: Map[String, akka.actor.FunctionRef] = functionRefs
+ val added: scala.collection.immutable.Map[String, akka.actor.FunctionRef] = old.updated(childPath.name, ref)
if (!Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.functionRefsOffset, old, added)) rec()
}
rec()
@@ -77,12 +77,12 @@ private[akka] trait Children { this: ActorCell ⇒
private[akka] def removeFunctionRef(ref: FunctionRef): Boolean = {
require(ref.path.parent eq self.path, "trying to remove FunctionRef from wrong ActorCell")
- val name = ref.path.name
+ val name: String = ref.path.name
@tailrec def rec(): Boolean = {
- val old = functionRefs
+ val old: Map[String, akka.actor.FunctionRef] = functionRefs
if (!old.contains(name)) false
else {
- val removed = old - name
+ val removed: scala.collection.immutable.Map[String, akka.actor.FunctionRef] = old - name
if (!Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.functionRefsOffset, old, removed)) rec()
else {
ref.stop()
@@ -94,24 +94,24 @@ private[akka] trait Children { this: ActorCell ⇒
}
protected def stopFunctionRefs(): Unit = {
- val refs = Unsafe.instance.getAndSetObject(this, AbstractActorCell.functionRefsOffset, Map.empty).asInstanceOf[Map[String, FunctionRef]]
+ val refs: Map[String, akka.actor.FunctionRef] = Unsafe.instance.getAndSetObject(this, AbstractActorCell.functionRefsOffset, Map.empty).asInstanceOf[Map[String, FunctionRef]]
refs.valuesIterator.foreach(_.stop())
}
@volatile private var _nextNameDoNotCallMeDirectly = 0L
final protected def randomName(sb: java.lang.StringBuilder): String = {
- val num = Unsafe.instance.getAndAddLong(this, AbstractActorCell.nextNameOffset, 1)
+ val num: Long = Unsafe.instance.getAndAddLong(this, AbstractActorCell.nextNameOffset, 1)
Helpers.base64(num, sb)
}
final protected def randomName(): String = {
- val num = Unsafe.instance.getAndAddLong(this, AbstractActorCell.nextNameOffset, 1)
+ val num: Long = Unsafe.instance.getAndAddLong(this, AbstractActorCell.nextNameOffset, 1)
Helpers.base64(num)
}
final def stop(actor: ActorRef): Unit = {
if (childrenRefs.getByRef(actor).isDefined) {
@tailrec def shallDie(ref: ActorRef): Boolean = {
- val c = childrenRefs
+ val c: akka.actor.dungeon.ChildrenContainer = childrenRefs
swapChildrenRefs(c, c.shallDie(ref)) || shallDie(ref)
}
@@ -130,22 +130,22 @@ private[akka] trait Children { this: ActorCell ⇒
Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.childrenOffset, oldChildren, newChildren)
@tailrec final def reserveChild(name: String): Boolean = {
- val c = childrenRefs
+ val c: akka.actor.dungeon.ChildrenContainer = childrenRefs
swapChildrenRefs(c, c.reserve(name)) || reserveChild(name)
}
@tailrec final protected def unreserveChild(name: String): Boolean = {
- val c = childrenRefs
+ val c: akka.actor.dungeon.ChildrenContainer = childrenRefs
swapChildrenRefs(c, c.unreserve(name)) || unreserveChild(name)
}
@tailrec final def initChild(ref: ActorRef): Option[ChildRestartStats] = {
- val cc = childrenRefs
+ val cc: akka.actor.dungeon.ChildrenContainer = childrenRefs
cc.getByName(ref.path.name) match {
case old @ Some(_: ChildRestartStats) ⇒ old.asInstanceOf[Option[ChildRestartStats]]
case Some(ChildNameReserved) ⇒
- val crs = ChildRestartStats(ref)
- val name = ref.path.name
+ val crs: akka.actor.ChildRestartStats = ChildRestartStats(ref)
+ val name: String = ref.path.name
if (swapChildrenRefs(cc, cc.add(name, crs))) Some(crs) else initChild(ref)
case None ⇒ None
}
@@ -165,11 +165,11 @@ private[akka] trait Children { this: ActorCell ⇒
* ActorCell-internal API
*/
- protected def isNormal = childrenRefs.isNormal
+ protected def isNormal: Boolean = childrenRefs.isNormal
- protected def isTerminating = childrenRefs.isTerminating
+ protected def isTerminating: Boolean = childrenRefs.isTerminating
- protected def waitingForChildrenOrNull = childrenRefs match {
+ protected def waitingForChildrenOrNull: akka.actor.dungeon.ChildrenContainer.SuspendReason with akka.actor.dungeon.ChildrenContainer.WaitingForChildren = childrenRefs match {
case TerminatingChildrenContainer(_, _, w: WaitingForChildren) ⇒ w
case _ ⇒ null
}
@@ -210,8 +210,8 @@ private[akka] trait Children { this: ActorCell ⇒
protected def removeChildAndGetStateChange(child: ActorRef): Option[SuspendReason] = {
@tailrec def removeChild(ref: ActorRef): ChildrenContainer = {
- val c = childrenRefs
- val n = c.remove(ref)
+ val c: akka.actor.dungeon.ChildrenContainer = childrenRefs
+ val n: akka.actor.dungeon.ChildrenContainer = c.remove(ref)
if (swapChildrenRefs(c, n)) n else removeChild(ref)
}
@@ -244,17 +244,17 @@ private[akka] trait Children { this: ActorCell ⇒
private def makeChild(cell: ActorCell, props: Props, name: String, async: Boolean, systemService: Boolean): ActorRef = {
if (cell.system.settings.SerializeAllCreators && !systemService && props.deploy.scope != LocalScope)
try {
- val ser = SerializationExtension(cell.system)
+ val ser: akka.serialization.Serialization = SerializationExtension(cell.system)
props.args forall (arg ⇒
arg == null ||
arg.isInstanceOf[NoSerializationVerificationNeeded] ||
{
- val o = arg.asInstanceOf[AnyRef]
- val serializer = ser.findSerializerFor(o)
- val bytes = serializer.toBinary(o)
+ val o: AnyRef = arg.asInstanceOf[AnyRef]
+ val serializer: akka.serialization.Serializer = ser.findSerializerFor(o)
+ val bytes: Array[Byte] = serializer.toBinary(o)
serializer match {
case ser2: SerializerWithStringManifest ⇒
- val manifest = ser2.manifest(o)
+ val manifest: String = ser2.manifest(o)
ser.deserialize(bytes, serializer.identifier, manifest).get != null
case _ ⇒
ser.deserialize(bytes, arg.getClass).get != null
@@ -271,9 +271,9 @@ private[akka] trait Children { this: ActorCell ⇒
else {
reserveChild(name)
// this name will either be unreserved or overwritten with a real child below
- val actor =
+ val actor: akka.actor.InternalActorRef =
try {
- val childPath = new ChildActorPath(cell.self.path, name, ActorCell.newUid())
+ val childPath: akka.actor.ChildActorPath = new ChildActorPath(cell.self.path, name, ActorCell.newUid())
cell.provider.actorOf(cell.systemImpl, props, cell.self, childPath,
systemService = systemService, deploy = None, lookupDeploy = true, async = async)
} catch {
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala b/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala
index 62a6e8d..6f1e21e 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala
@@ -50,21 +50,21 @@ private[akka] object ChildrenContainer {
case object Termination extends SuspendReason
class ChildRestartsIterable(stats: immutable.MapLike[_, ChildStats, _]) extends PartialImmutableValuesIterable[ChildStats, ChildRestartStats] {
- override final def apply(c: ChildStats) = c.asInstanceOf[ChildRestartStats]
- override final def isDefinedAt(c: ChildStats) = c.isInstanceOf[ChildRestartStats]
- override final def valuesIterator = stats.valuesIterator
+ override final def apply(c: ChildStats): akka.actor.ChildRestartStats = c.asInstanceOf[ChildRestartStats]
+ override final def isDefinedAt(c: ChildStats): Boolean = c.isInstanceOf[ChildRestartStats]
+ override final def valuesIterator: Iterator[akka.actor.ChildStats] = stats.valuesIterator
}
class ChildrenIterable(stats: immutable.MapLike[_, ChildStats, _]) extends PartialImmutableValuesIterable[ChildStats, ActorRef] {
- override final def apply(c: ChildStats) = c.asInstanceOf[ChildRestartStats].child
- override final def isDefinedAt(c: ChildStats) = c.isInstanceOf[ChildRestartStats]
- override final def valuesIterator = stats.valuesIterator
+ override final def apply(c: ChildStats): akka.actor.ActorRef = c.asInstanceOf[ChildRestartStats].child
+ override final def isDefinedAt(c: ChildStats): Boolean = c.isInstanceOf[ChildRestartStats]
+ override final def valuesIterator: Iterator[akka.actor.ChildStats] = stats.valuesIterator
}
trait WaitingForChildren
trait EmptyChildrenContainer extends ChildrenContainer {
- val emptyStats = immutable.TreeMap.empty[String, ChildStats]
+ val emptyStats: scala.collection.immutable.TreeMap[String, akka.actor.ChildStats] = immutable.TreeMap.empty[String, ChildStats]
override def add(name: String, stats: ChildRestartStats): ChildrenContainer = new NormalChildrenContainer(emptyStats.updated(name, stats))
override def remove(child: ActorRef): ChildrenContainer = this
override def getByName(name: String): Option[ChildRestartStats] = None
@@ -134,7 +134,7 @@ private[akka] object ChildrenContainer {
case _ ⇒ this
}
- override def toString =
+ override def toString: String =
if (c.size > 20) c.size + " children"
else c.mkString("children:\n ", "\n ", "")
}
@@ -161,7 +161,7 @@ private[akka] object ChildrenContainer {
override def add(name: String, stats: ChildRestartStats): ChildrenContainer = copy(c.updated(name, stats))
override def remove(child: ActorRef): ChildrenContainer = {
- val t = toDie - child
+ val t: scala.collection.immutable.Set[akka.actor.ActorRef] = toDie - child
if (t.isEmpty) reason match {
case Termination ⇒ TerminatedChildrenContainer
case _ ⇒ NormalChildrenContainer(c - child.path.name)
@@ -200,7 +200,7 @@ private[akka] object ChildrenContainer {
override def isTerminating: Boolean = reason == Termination
override def isNormal: Boolean = reason == UserRequest
- override def toString =
+ override def toString: String =
if (c.size > 20) c.size + " children"
else c.mkString("children (" + toDie.size + " terminating):\n ", "\n ", "\n") + toDie
}
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala b/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala
index dfd9271..1f0b80b 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala
@@ -159,8 +159,8 @@ private[akka] trait DeathWatch { this: ActorCell ⇒
}
protected def addWatcher(watchee: ActorRef, watcher: ActorRef): Unit = {
- val watcheeSelf = watchee == self
- val watcherSelf = watcher == self
+ val watcheeSelf: Boolean = watchee == self
+ val watcherSelf: Boolean = watcher == self
if (watcheeSelf && !watcherSelf) {
if (!watchedBy.contains(watcher)) maintainAddressTerminatedSubscription(watcher) {
@@ -175,8 +175,8 @@ private[akka] trait DeathWatch { this: ActorCell ⇒
}
protected def remWatcher(watchee: ActorRef, watcher: ActorRef): Unit = {
- val watcheeSelf = watchee == self
- val watcherSelf = watcher == self
+ val watcheeSelf: Boolean = watchee == self
+ val watcherSelf: Boolean = watcher == self
if (watcheeSelf && !watcherSelf) {
if (watchedBy.contains(watcher)) maintainAddressTerminatedSubscription(watcher) {
@@ -214,7 +214,7 @@ private[akka] trait DeathWatch { this: ActorCell ⇒
* block removes the last non-local ref from watching and watchedBy.
*/
private def maintainAddressTerminatedSubscription[T](change: ActorRef = null)(block: ⇒ T): T = {
- def isNonLocal(ref: ActorRef) = ref match {
+ def isNonLocal(ref: ActorRef): Boolean = ref match {
case null ⇒ true
case a: InternalActorRef if !a.isLocal ⇒ true
case _ ⇒ false
@@ -222,9 +222,9 @@ private[akka] trait DeathWatch { this: ActorCell ⇒
if (isNonLocal(change)) {
def hasNonLocalAddress: Boolean = ((watching.keysIterator exists isNonLocal) || (watchedBy exists isNonLocal))
- val had = hasNonLocalAddress
- val result = block
- val has = hasNonLocalAddress
+ val had: Boolean = hasNonLocalAddress
+ val result: T = block
+ val has: Boolean = hasNonLocalAddress
if (had && !has) unsubscribeAddressTerminated()
else if (!had && has) subscribeAddressTerminated()
result
@@ -240,6 +240,6 @@ private[akka] trait DeathWatch { this: ActorCell ⇒
}
private[akka] class UndefinedUidActorRef(ref: ActorRef) extends MinimalActorRef {
- override val path = ref.path.withUid(ActorCell.undefinedUid)
- override def provider = throw new UnsupportedOperationException("UndefinedUidActorRef does not provide")
+ override val path: akka.actor.ActorPath = ref.path.withUid(ActorCell.undefinedUid)
+ override def provider: Nothing = throw new UnsupportedOperationException("UndefinedUidActorRef does not provide")
}
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala b/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala
index 0587576..3fc6267 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala
@@ -27,7 +27,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒
@inline final def mailbox: Mailbox = Unsafe.instance.getObjectVolatile(this, AbstractActorCell.mailboxOffset).asInstanceOf[Mailbox]
@tailrec final def swapMailbox(newMailbox: Mailbox): Mailbox = {
- val oldMailbox = mailbox
+ val oldMailbox: akka.dispatch.Mailbox = mailbox
if (!Unsafe.instance.compareAndSwapObject(this, AbstractActorCell.mailboxOffset, oldMailbox, newMailbox)) swapMailbox(newMailbox)
else oldMailbox
}
@@ -48,7 +48,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒
* Create the mailbox and enqueue the Create() message to ensure that
* this is processed before anything else.
*/
- val mbox = dispatcher.createMailbox(this, mailboxType)
+ val mbox: akka.dispatch.Mailbox = dispatcher.createMailbox(this, mailboxType)
/*
* The mailboxType was calculated taking into account what the MailboxType
@@ -57,13 +57,13 @@ private[akka] trait Dispatch { this: ActorCell ⇒
*/
// we need to delay the failure to the point of actor creation so we can handle
// it properly in the normal way
- val actorClass = props.actorClass
- val createMessage = mailboxType match {
+ val actorClass: Class[_ <: akka.actor.Actor] = props.actorClass
+ val createMessage: akka.dispatch.sysmsg.Create = mailboxType match {
case _: ProducesMessageQueue[_] if system.mailboxes.hasRequiredType(actorClass) ⇒
- val req = system.mailboxes.getRequiredType(actorClass)
+ val req: Class[_] = system.mailboxes.getRequiredType(actorClass)
if (req isInstance mbox.messageQueue) Create(None)
else {
- val gotType = if (mbox.messageQueue == null) "null" else mbox.messageQueue.getClass.getName
+ val gotType: String = if (mbox.messageQueue == null) "null" else mbox.messageQueue.getClass.getName
Create(Some(ActorInitializationException(
self,
s"Actor [$self] requires mailbox type [$req] got [$gotType]")))
@@ -85,11 +85,11 @@ private[akka] trait Dispatch { this: ActorCell ⇒
}
final def initWithFailure(failure: Throwable): this.type = {
- val mbox = dispatcher.createMailbox(this, new UnboundedMailbox)
+ val mbox: akka.dispatch.Mailbox = dispatcher.createMailbox(this, new UnboundedMailbox)
swapMailbox(mbox)
mailbox.setActor(this)
// ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
- val createMessage = Create(Some(ActorInitializationException(self, "failure while creating ActorCell", failure)))
+ val createMessage: akka.dispatch.sysmsg.Create = Create(Some(ActorInitializationException(self, "failure while creating ActorCell", failure)))
mailbox.systemEnqueue(self, createMessage)
this
}
@@ -108,7 +108,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒
system.eventStream.publish(Error(e, self.path.toString, clazz(actor), "interrupted during message send"))
Thread.currentThread.interrupt()
case NonFatal(e) ⇒
- val message = e match {
+ val message: String = e match {
case n: NoStackTrace ⇒ "swallowing exception during message send: " + n.getMessage
case _ ⇒ "swallowing exception during message send" // stack trace includes message
}
@@ -129,7 +129,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒
def sendMessage(msg: Envelope): Unit =
try {
- val msgToDispatch =
+ val msgToDispatch: akka.dispatch.Envelope =
if (system.settings.SerializeAllMessages) serializeAndDeserialize(msg)
else msg
@@ -138,7 +138,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒
private def serializeAndDeserialize(envelope: Envelope): Envelope = {
- val unwrappedMessage =
+ val unwrappedMessage: AnyRef =
(envelope.message match {
case DeadLetter(wrapped, _, _) ⇒ wrapped
case other ⇒ other
@@ -147,7 +147,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒
unwrappedMessage match {
case _: NoSerializationVerificationNeeded ⇒ envelope
case msg ⇒
- val deserializedMsg = serializeAndDeserializePayload(msg)
+ val deserializedMsg: AnyRef = serializeAndDeserializePayload(msg)
envelope.message match {
case dl: DeadLetter ⇒ envelope.copy(message = dl.copy(message = deserializedMsg))
case _ ⇒ envelope.copy(message = deserializedMsg)
@@ -156,15 +156,15 @@ private[akka] trait Dispatch { this: ActorCell ⇒
}
private def serializeAndDeserializePayload(obj: AnyRef): AnyRef = {
- val s = SerializationExtension(system)
- val serializer = s.findSerializerFor(obj)
+ val s: akka.serialization.Serialization = SerializationExtension(system)
+ val serializer: akka.serialization.Serializer = s.findSerializerFor(obj)
if (serializer.isInstanceOf[DisabledJavaSerializer] && !s.shouldWarnAboutJavaSerializer(obj.getClass, serializer))
obj // skip check for known "local" messages
else {
- val bytes = serializer.toBinary(obj)
+ val bytes: Array[Byte] = serializer.toBinary(obj)
serializer match {
case ser2: SerializerWithStringManifest ⇒
- val manifest = ser2.manifest(obj)
+ val manifest: String = ser2.manifest(obj)
s.deserialize(bytes, serializer.identifier, manifest).get
case _ ⇒
s.deserialize(bytes, obj.getClass).get
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala b/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala
index bf05cf6..250df5f 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala
@@ -58,15 +58,15 @@ private[akka] trait FaultHandling { this: ActorCell ⇒
"changing Recreate into Create after " + cause))
faultCreate()
} else if (isNormal) {
- val failedActor = actor
+ val failedActor: akka.actor.Actor = actor
if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(failedActor), "restarting"))
if (failedActor ne null) {
- val optionalMessage = if (currentMessage ne null) Some(currentMessage.message) else None
+ val optionalMessage: Option[Any] = if (currentMessage ne null) Some(currentMessage.message) else None
try {
// if the actor fails in preRestart, we can do nothing but log it: it’s best-effort
if (failedActor.context ne null) failedActor.aroundPreRestart(cause, optionalMessage)
} catch handleNonFatalOrInterruptedException { e ⇒
- val ex = PreRestartException(self, e, cause, optionalMessage)
+ val ex: akka.actor.PreRestartException = PreRestartException(self, e, cause, optionalMessage)
publish(Error(ex, self.path.toString, clazz(failedActor), e.getMessage))
} finally {
clearActorFields(failedActor, recreate = true)
@@ -105,7 +105,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒
"changing Resume into Restart after " + causedByFailure))
faultRecreate(causedByFailure)
} else {
- val perp = perpetrator
+ val perp: akka.actor.ActorRef = perpetrator
// done always to keep that suspend counter balanced
// must happen “atomically”
try resumeNonRecursive()
@@ -157,7 +157,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒
}
}
- val wasTerminating = isTerminating
+ val wasTerminating: Boolean = isTerminating
if (setChildrenTerminationReason(ChildrenContainer.Termination)) {
if (!wasTerminating) {
@@ -201,7 +201,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒
}
private def finishTerminate() {
- val a = actor
+ val a: akka.actor.Actor = actor
/* The following order is crucial for things to work properly. Only change this if you're very confident and lucky.
*
* Please note that if a parent is also a watcher then ChildTerminated and Terminated must be processed in this
@@ -226,13 +226,13 @@ private[akka] trait FaultHandling { this: ActorCell ⇒
private def finishRecreate(cause: Throwable, failedActor: Actor): Unit = {
// need to keep a snapshot of the surviving children before the new actor instance creates new ones
- val survivors = children
+ val survivors: scala.collection.immutable.Iterable[akka.actor.ActorRef] = children
try {
try resumeNonRecursive()
finally clearFailed() // must happen in any case, so that failure is propagated
- val freshActor = newActor()
+ val freshActor: akka.actor.Actor = newActor()
actor = freshActor // this must happen before postRestart has a chance to fail
if (freshActor eq failedActor) setActorFields(freshActor, this, self) // If the creator returns the same instance, we need to restore our nulled out fields.
@@ -270,7 +270,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒
}
final protected def handleChildTerminated(child: ActorRef): Unit = {
- val status = removeChildAndGetStateChange(child)
+ val status: Option[akka.actor.dungeon.ChildrenContainer.SuspendReason] = removeChildAndGetStateChange(child)
/*
* if this fails, we do nothing in case of terminating/restarting state,
* otherwise tell the supervisor etc. (in that second case, the match
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala b/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala
index a39f1d0..c334e68 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala
@@ -27,12 +27,12 @@ private[akka] trait ReceiveTimeout { this: ActorCell ⇒
final def setReceiveTimeout(timeout: Duration): Unit = receiveTimeoutData = receiveTimeoutData.copy(_1 = timeout)
final def checkReceiveTimeout() {
- val recvtimeout = receiveTimeoutData
+ val recvtimeout: (scala.concurrent.duration.Duration, akka.actor.Cancellable) = receiveTimeoutData
//Only reschedule if desired and there are currently no more messages to be processed
if (!mailbox.hasMessages) recvtimeout._1 match {
case f: FiniteDuration ⇒
recvtimeout._2.cancel() //Cancel any ongoing future
- val task = system.scheduler.scheduleOnce(f, self, akka.actor.ReceiveTimeout)(this.dispatcher)
+ val task: akka.actor.Cancellable = system.scheduler.scheduleOnce(f, self, akka.actor.ReceiveTimeout)(this.dispatcher)
receiveTimeoutData = (f, task)
case _ ⇒ cancelReceiveTimeout()
}
diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala b/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala
index a2ba58c..fa2b4ba 100644
--- a/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala
+++ b/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala
@@ -43,16 +43,16 @@ import akka.util.OptionVal
case Some(t) ⇒ cancelTimer(t)
case None ⇒
}
- val nextGen = nextTimerGen()
+ val nextGen: Int = nextTimerGen()
- val timerMsg = TimerMsg(key, nextGen, this)
- val task =
+ val timerMsg: akka.actor.TimerSchedulerImpl.TimerMsg = TimerMsg(key, nextGen, this)
+ val task: akka.actor.Cancellable =
if (repeat)
ctx.system.scheduler.schedule(timeout, timeout, ctx.self, timerMsg)(ctx.dispatcher)
else
ctx.system.scheduler.scheduleOnce(timeout, ctx.self, timerMsg)(ctx.dispatcher)
- val nextTimer = Timer(key, msg, repeat, nextGen, task)
+ val nextTimer: akka.actor.TimerSchedulerImpl.Timer = Timer(key, msg, repeat, nextGen, task)
log.debug("Start timer [{}] with generation [{}]", key, nextGen)
timers = timers.updated(key, nextTimer)
}
diff --git a/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala b/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala
index 32f7618..cf4e437 100644
--- a/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala
+++ b/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala
@@ -27,7 +27,7 @@ abstract class Setup {
object ActorSystemSetup {
- val empty = new ActorSystemSetup(Map.empty)
+ val empty: akka.actor.setup.ActorSystemSetup = new ActorSystemSetup(Map.empty)
/**
* Scala API: Create an [[ActorSystemSetup]] containing all the provided settings
@@ -61,7 +61,7 @@ final class ActorSystemSetup private[akka] (setups: Map[Class[_], AnyRef]) {
* Scala API: Extract a concrete [[Setup]] of type `T` if it is defined in the settings.
*/
def get[T <: Setup: ClassTag]: Option[T] = {
- val clazz = implicitly[ClassTag[T]].runtimeClass
+ val clazz: Class[_] = implicitly[ClassTag[T]].runtimeClass
setups.get(clazz).map(_.asInstanceOf[T])
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala
index 28dd212..5a2928b 100644
--- a/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala
@@ -60,7 +60,7 @@ private[akka] object MessageDispatcher {
// dispatcher debugging helper using println (see below)
// since this is a compile-time constant, scalac will elide code behind if (MessageDispatcher.debug) (RK checked with 2.9.1)
final val debug = false // Deliberately without type ascription to make it a compile-time constant
- lazy val actors = new Index[MessageDispatcher, ActorRef](16, new ju.Comparator[ActorRef] {
+ lazy val actors: akka.util.Index[akka.dispatch.MessageDispatcher, akka.actor.ActorRef] = new Index[MessageDispatcher, ActorRef](16, new ju.Comparator[ActorRef] {
override def compare(a: ActorRef, b: ActorRef): Int = a.compareTo(b)
})
def printActors(): Unit =
@@ -69,12 +69,12 @@ private[akka] object MessageDispatcher {
d ← actors.keys
a ← { println(d + " inhabitants: " + d.inhabitants); actors.valueIterator(d) }
} {
- val status = if (a.isTerminated) " (terminated)" else " (alive)"
- val messages = a match {
+ val status: String = if (a.isTerminated) " (terminated)" else " (alive)"
+ val messages: String = a match {
case r: ActorRefWithCell ⇒ " " + r.underlying.numberOfMessages + " messages"
case _ ⇒ " " + a.getClass
}
- val parent = a match {
+ val parent: String = a match {
case i: InternalActorRef ⇒ ", parent: " + i.getParent
case _ ⇒ ""
}
@@ -89,19 +89,19 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
import MessageDispatcher._
import configurator.prerequisites
- val mailboxes = prerequisites.mailboxes
- val eventStream = prerequisites.eventStream
+ val mailboxes: akka.dispatch.Mailboxes = prerequisites.mailboxes
+ val eventStream: akka.event.EventStream = prerequisites.eventStream
@volatile private[this] var _inhabitantsDoNotCallMeDirectly: Long = _ // DO NOT TOUCH!
@volatile private[this] var _shutdownScheduleDoNotCallMeDirectly: Int = _ // DO NOT TOUCH!
private final def addInhabitants(add: Long): Long = {
- val old = Unsafe.instance.getAndAddLong(this, inhabitantsOffset, add)
- val ret = old + add
+ val old: Long = Unsafe.instance.getAndAddLong(this, inhabitantsOffset, add)
+ val ret: Long = old + add
if (ret < 0) {
// We haven't succeeded in decreasing the inhabitants yet but the simple fact that we're trying to
// go below zero means that there is an imbalance and we might as well throw the exception
- val e = new IllegalStateException("ACTOR SYSTEM CORRUPTED!!! A dispatcher can't have less than 0 inhabitants!")
+ val e: IllegalStateException = new IllegalStateException("ACTOR SYSTEM CORRUPTED!!! A dispatcher can't have less than 0 inhabitants!")
reportFailure(e)
throw e
}
@@ -140,7 +140,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
final def detach(actor: ActorCell): Unit = try unregister(actor) finally ifSensibleToDoSoThenScheduleShutdown()
final protected def resubmitOnBlock: Boolean = true // We want to avoid starvation
final override protected def unbatchedExecute(r: Runnable): Unit = {
- val invocation = TaskInvocation(eventStream, r, taskCleanup)
+ val invocation: akka.dispatch.TaskInvocation = TaskInvocation(eventStream, r, taskCleanup)
addInhabitants(+1)
try {
executeTask(invocation)
@@ -205,7 +205,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
protected[akka] def unregister(actor: ActorCell) {
if (debug) actors.remove(this, actor.self)
addInhabitants(-1)
- val mailBox = actor.swapMailbox(mailboxes.deadLetterMailbox)
+ val mailBox: akka.dispatch.Mailbox = actor.swapMailbox(mailboxes.deadLetterMailbox)
mailBox.becomeClosed()
mailBox.cleanUp()
}
@@ -241,7 +241,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
* After the call to this method, the dispatcher mustn't begin any new message processing for the specified reference
*/
protected[akka] def suspend(actor: ActorCell): Unit = {
- val mbox = actor.mailbox
+ val mbox: akka.dispatch.Mailbox = actor.mailbox
if ((mbox.actor eq actor) && (mbox.dispatcher eq this))
mbox.suspend()
}
@@ -250,7 +250,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
* After the call to this method, the dispatcher must begin any new message processing for the specified reference
*/
protected[akka] def resume(actor: ActorCell): Unit = {
- val mbox = actor.mailbox
+ val mbox: akka.dispatch.Mailbox = actor.mailbox
if ((mbox.actor eq actor) && (mbox.dispatcher eq this) && mbox.resume())
registerForExecution(mbox, false, false)
}
@@ -290,7 +290,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
/**
* INTERNAL API
*/
- @inline protected[akka] final val isThroughputDeadlineTimeDefined = throughputDeadlineTime.toMillis > 0
+ @inline protected[akka] final val isThroughputDeadlineTimeDefined: Boolean = throughputDeadlineTime.toMillis > 0
/**
* INTERNAL API
@@ -332,7 +332,7 @@ abstract class MessageDispatcherConfigurator(_config: Config, val prerequisites:
case "affinity-pool-executor" ⇒ new AffinityPoolConfigurator(config.getConfig("affinity-pool-executor"), prerequisites)
case fqcn ⇒
- val args = List(
+ val args: List[(Class[_ >: akka.dispatch.DispatcherPrerequisites with com.typesafe.config.Config <: Object], Object)] = List(
classOf[Config] → config,
classOf[DispatcherPrerequisites] → prerequisites)
prerequisites.dynamicAccess.createInstanceFor[ExecutorServiceConfigurator](fqcn, args).recover({
@@ -356,7 +356,7 @@ class ThreadPoolExecutorConfigurator(config: Config, prerequisites: DispatcherPr
protected def createThreadPoolConfigBuilder(config: Config, prerequisites: DispatcherPrerequisites): ThreadPoolConfigBuilder = {
import akka.util.Helpers.ConfigOps
- val builder =
+ val builder: akka.dispatch.ThreadPoolConfigBuilder =
ThreadPoolConfigBuilder(ThreadPoolConfig())
.setKeepAliveTime(config.getMillisDuration("keep-alive-time"))
.setAllowCoreThreadTimeout(config getBoolean "allow-core-timeout")
diff --git a/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala
index 2d7bd97..2335097 100644
--- a/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala
@@ -47,7 +47,7 @@ private[akka] class BalancingDispatcher(
*/
private[akka] val team = new ConcurrentSkipListSet[ActorCell](
Helpers.identityHashComparator(new Comparator[ActorCell] {
- def compare(l: ActorCell, r: ActorCell) = l.self.path compareTo r.self.path
+ def compare(l: ActorCell, r: ActorCell): Int = l.self.path compareTo r.self.path
}))
/**
@@ -58,12 +58,12 @@ private[akka] class BalancingDispatcher(
private class SharingMailbox(val system: ActorSystemImpl, _messageQueue: MessageQueue)
extends Mailbox(_messageQueue) with DefaultSystemMessageQueue {
override def cleanUp(): Unit = {
- val dlq = mailboxes.deadLetterMailbox
+ val dlq: akka.dispatch.Mailbox = mailboxes.deadLetterMailbox
//Don't call the original implementation of this since it scraps all messages, and we don't want to do that
var messages = systemDrain(new LatestFirstSystemMessageList(NoMessage))
while (messages.nonEmpty) {
// message must be “virgin” before being able to systemEnqueue again
- val message = messages.head
+ val message: akka.dispatch.sysmsg.SystemMessage = messages.head
messages = messages.tail
message.unlink()
dlq.systemEnqueue(system.deadLetters, message)
@@ -85,7 +85,7 @@ private[akka] class BalancingDispatcher(
teamWork()
}
- override protected[akka] def dispatch(receiver: ActorCell, invocation: Envelope) = {
+ override protected[akka] def dispatch(receiver: ActorCell, invocation: Envelope): Unit = {
messageQueue.enqueue(receiver.self, invocation)
if (!registerForExecution(receiver.mailbox, false, false)) teamWork()
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala b/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala
index f69de50..b5dfae5 100644
--- a/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala
@@ -57,7 +57,7 @@ private[akka] trait BatchingExecutor extends Executor {
}
protected final def resubmitUnbatched(): Boolean = {
- val current = _tasksLocal.get()
+ val current: BatchingExecutor.this.AbstractBatch = _tasksLocal.get()
_tasksLocal.remove()
if ((current eq this) && !current.isEmpty) { // Resubmit ourselves if something bad happened and we still have work to do
unbatchedExecute(current) //TODO what if this submission fails?
@@ -85,7 +85,7 @@ private[akka] trait BatchingExecutor extends Executor {
override final def run(): Unit = {
require(_tasksLocal.get eq null)
_tasksLocal set this // Install ourselves as the current batch
- val firstInvocation = _blockContext.get eq null
+ val firstInvocation: Boolean = _blockContext.get eq null
if (firstInvocation) _blockContext.set(BlockContext.current)
BlockContext.withBlockContext(this) {
try processBatch(this) catch {
diff --git a/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala b/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala
index 345c7d7..4462d2e 100644
--- a/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala
@@ -15,7 +15,7 @@ import scala.util.{ Failure, Success, Try }
* INTERNAL API
*/
private[akka] object CachingConfig {
- val emptyConfig = ConfigFactory.empty()
+ val emptyConfig: com.typesafe.config.Config = ConfigFactory.empty()
sealed abstract trait PathEntry {
val valid: Boolean
@@ -25,9 +25,9 @@ private[akka] object CachingConfig {
final case class ValuePathEntry(valid: Boolean, exists: Boolean, config: Config = emptyConfig) extends PathEntry
final case class StringPathEntry(valid: Boolean, exists: Boolean, config: Config, value: String) extends PathEntry
- val invalidPathEntry = ValuePathEntry(false, true)
- val nonExistingPathEntry = ValuePathEntry(true, false)
- val emptyPathEntry = ValuePathEntry(true, true)
+ val invalidPathEntry: akka.dispatch.CachingConfig.ValuePathEntry = ValuePathEntry(false, true)
+ val nonExistingPathEntry: akka.dispatch.CachingConfig.ValuePathEntry = ValuePathEntry(true, false)
+ val emptyPathEntry: akka.dispatch.CachingConfig.ValuePathEntry = ValuePathEntry(true, true)
}
/**
@@ -50,7 +50,7 @@ private[akka] class CachingConfig(_config: Config) extends Config {
private def getPathEntry(path: String): PathEntry = entryMap.get(path) match {
case null ⇒
- val ne = Try { config.hasPath(path) } match {
+ val ne: Product with Serializable with akka.dispatch.CachingConfig.PathEntry = Try { config.hasPath(path) } match {
case Failure(e) ⇒ invalidPathEntry
case Success(false) ⇒ nonExistingPathEntry
case _ ⇒
@@ -77,22 +77,22 @@ private[akka] class CachingConfig(_config: Config) extends Config {
config.checkValid(reference, restrictToPaths: _*)
}
- def root() = config.root()
+ def root(): com.typesafe.config.ConfigObject = config.root()
- def origin() = config.origin()
+ def origin(): com.typesafe.config.ConfigOrigin = config.origin()
- def withFallback(other: ConfigMergeable) = new CachingConfig(config.withFallback(other))
+ def withFallback(other: ConfigMergeable): akka.dispatch.CachingConfig = new CachingConfig(config.withFallback(other))
- def resolve() = resolve(ConfigResolveOptions.defaults())
+ def resolve(): com.typesafe.config.Config = resolve(ConfigResolveOptions.defaults())
- def resolve(options: ConfigResolveOptions) = {
- val resolved = config.resolve(options)
+ def resolve(options: ConfigResolveOptions): com.typesafe.config.Config = {
+ val resolved: com.typesafe.config.Config = config.resolve(options)
if (resolved eq config) this
else new CachingConfig(resolved)
}
- def hasPath(path: String) = {
- val entry = getPathEntry(path)
+ def hasPath(path: String): Boolean = {
+ val entry: akka.dispatch.CachingConfig.PathEntry = getPathEntry(path)
if (entry.valid)
entry.exists
else // run the real code to get proper exceptions
@@ -101,21 +101,21 @@ private[akka] class CachingConfig(_config: Config) extends Config {
def hasPathOrNull(path: String): Boolean = config.hasPathOrNull(path)
- def isEmpty = config.isEmpty
+ def isEmpty: Boolean = config.isEmpty
- def entrySet() = config.entrySet()
+ def entrySet(): java.util.Set[java.util.Map.Entry[String, com.typesafe.config.ConfigValue]] = config.entrySet()
- def getBoolean(path: String) = config.getBoolean(path)
+ def getBoolean(path: String): Boolean = config.getBoolean(path)
- def getNumber(path: String) = config.getNumber(path)
+ def getNumber(path: String): Number = config.getNumber(path)
- def getInt(path: String) = config.getInt(path)
+ def getInt(path: String): Int = config.getInt(path)
- def getLong(path: String) = config.getLong(path)
+ def getLong(path: String): Long = config.getLong(path)
- def getDouble(path: String) = config.getDouble(path)
+ def getDouble(path: String): Double = config.getDouble(path)
- def getString(path: String) = {
+ def getString(path: String): String = {
getPathEntry(path) match {
case StringPathEntry(_, _, _, string) ⇒
string
@@ -123,75 +123,75 @@ private[akka] class CachingConfig(_config: Config) extends Config {
}
}
- def getObject(path: String) = config.getObject(path)
+ def getObject(path: String): com.typesafe.config.ConfigObject = config.getObject(path)
- def getConfig(path: String) = config.getConfig(path)
+ def getConfig(path: String): com.typesafe.config.Config = config.getConfig(path)
- def getAnyRef(path: String) = config.getAnyRef(path)
+ def getAnyRef(path: String): Object = config.getAnyRef(path)
- def getValue(path: String) = config.getValue(path)
+ def getValue(path: String): com.typesafe.config.ConfigValue = config.getValue(path)
- def getBytes(path: String) = config.getBytes(path)
+ def getBytes(path: String): Long = config.getBytes(path)
- def getMilliseconds(path: String) = config.getDuration(path, TimeUnit.MILLISECONDS)
+ def getMilliseconds(path: String): Long = config.getDuration(path, TimeUnit.MILLISECONDS)
- def getNanoseconds(path: String) = config.getDuration(path, TimeUnit.NANOSECONDS)
+ def getNanoseconds(path: String): Long = config.getDuration(path, TimeUnit.NANOSECONDS)
- def getList(path: String) = config.getList(path)
+ def getList(path: String): com.typesafe.config.ConfigList = config.getList(path)
- def getBooleanList(path: String) = config.getBooleanList(path)
+ def getBooleanList(path: String): java.util.List[Boolean] = config.getBooleanList(path)
- def getNumberList(path: String) = config.getNumberList(path)
+ def getNumberList(path: String): java.util.List[Number] = config.getNumberList(path)
- def getIntList(path: String) = config.getIntList(path)
+ def getIntList(path: String): java.util.List[Integer] = config.getIntList(path)
- def getLongList(path: String) = config.getLongList(path)
+ def getLongList(path: String): java.util.List[Long] = config.getLongList(path)
- def getDoubleList(path: String) = config.getDoubleList(path)
+ def getDoubleList(path: String): java.util.List[Double] = config.getDoubleList(path)
- def getStringList(path: String) = config.getStringList(path)
+ def getStringList(path: String): java.util.List[String] = config.getStringList(path)
- def getObjectList(path: String) = config.getObjectList(path)
+ def getObjectList(path: String): java.util.List[_ <: com.typesafe.config.ConfigObject] = config.getObjectList(path)
- def getConfigList(path: String) = config.getConfigList(path)
+ def getConfigList(path: String): java.util.List[_ <: com.typesafe.config.Config] = config.getConfigList(path)
- def getAnyRefList(path: String) = config.getAnyRefList(path)
+ def getAnyRefList(path: String): java.util.List[_] = config.getAnyRefList(path)
- def getBytesList(path: String) = config.getBytesList(path)
+ def getBytesList(path: String): java.util.List[Long] = config.getBytesList(path)
- def getMillisecondsList(path: String) = config.getDurationList(path, TimeUnit.MILLISECONDS)
+ def getMillisecondsList(path: String): java.util.List[Long] = config.getDurationList(path, TimeUnit.MILLISECONDS)
- def getNanosecondsList(path: String) = config.getDurationList(path, TimeUnit.NANOSECONDS)
+ def getNanosecondsList(path: String): java.util.List[Long] = config.getDurationList(path, TimeUnit.NANOSECONDS)
- def withOnlyPath(path: String) = new CachingConfig(config.withOnlyPath(path))
+ def withOnlyPath(path: String): akka.dispatch.CachingConfig = new CachingConfig(config.withOnlyPath(path))
- def withoutPath(path: String) = new CachingConfig(config.withoutPath(path))
+ def withoutPath(path: String): akka.dispatch.CachingConfig = new CachingConfig(config.withoutPath(path))
- def atPath(path: String) = new CachingConfig(config.atPath(path))
+ def atPath(path: String): akka.dispatch.CachingConfig = new CachingConfig(config.atPath(path))
- def atKey(key: String) = new CachingConfig(config.atKey(key))
+ def atKey(key: String): akka.dispatch.CachingConfig = new CachingConfig(config.atKey(key))
- def withValue(path: String, value: ConfigValue) = new CachingConfig(config.withValue(path, value))
+ def withValue(path: String, value: ConfigValue): akka.dispatch.CachingConfig = new CachingConfig(config.withValue(path, value))
- def getDuration(path: String, unit: TimeUnit) = config.getDuration(path, unit)
+ def getDuration(path: String, unit: TimeUnit): Long = config.getDuration(path, unit)
- def getDurationList(path: String, unit: TimeUnit) = config.getDurationList(path, unit)
+ def getDurationList(path: String, unit: TimeUnit): java.util.List[Long] = config.getDurationList(path, unit)
def getDuration(path: String): java.time.Duration = config.getDuration(path)
- def getDurationList(path: String) = config.getDurationList(path)
+ def getDurationList(path: String): java.util.List[java.time.Duration] = config.getDurationList(path)
def getIsNull(path: String): Boolean = config.getIsNull(path)
- def getMemorySize(path: String) = config.getMemorySize(path)
+ def getMemorySize(path: String): com.typesafe.config.ConfigMemorySize = config.getMemorySize(path)
- def getMemorySizeList(path: String) = config.getMemorySizeList(path)
+ def getMemorySizeList(path: String): java.util.List[com.typesafe.config.ConfigMemorySize] = config.getMemorySizeList(path)
- def isResolved() = config.isResolved()
+ def isResolved(): Boolean = config.isResolved()
- def resolveWith(source: Config, options: ConfigResolveOptions) = config.resolveWith(source, options)
+ def resolveWith(source: Config, options: ConfigResolveOptions): com.typesafe.config.Config = config.resolveWith(source, options)
- def resolveWith(source: Config) = config.resolveWith(source)
+ def resolveWith(source: Config): com.typesafe.config.Config = config.resolveWith(source)
override def getEnumList[T <: Enum[T]](enumClass: Class[T], path: String): util.List[T] = config.getEnumList(enumClass, path)
diff --git a/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala
index f17b0ca..7d4856b 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala
@@ -50,7 +50,7 @@ class Dispatcher(
* INTERNAL API
*/
protected[akka] def dispatch(receiver: ActorCell, invocation: Envelope): Unit = {
- val mbox = receiver.mailbox
+ val mbox: akka.dispatch.Mailbox = receiver.mailbox
mbox.enqueue(receiver.self, invocation)
registerForExecution(mbox, true, false)
}
@@ -59,7 +59,7 @@ class Dispatcher(
* INTERNAL API
*/
protected[akka] def systemDispatch(receiver: ActorCell, invocation: SystemMessage): Unit = {
- val mbox = receiver.mailbox
+ val mbox: akka.dispatch.Mailbox = receiver.mailbox
mbox.systemEnqueue(receiver.self, invocation)
registerForExecution(mbox, false, true)
}
@@ -98,8 +98,8 @@ class Dispatcher(
* INTERNAL API
*/
protected[akka] def shutdown: Unit = {
- val newDelegate = executorServiceDelegate.copy() // Doesn't matter which one we copy
- val es = esUpdater.getAndSet(this, newDelegate)
+ val newDelegate: Dispatcher.this.LazyExecutorServiceDelegate = executorServiceDelegate.copy() // Doesn't matter which one we copy
+ val es: Dispatcher.this.LazyExecutorServiceDelegate = esUpdater.getAndSet(this, newDelegate)
es.shutdown()
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala b/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala
index dd180f1..0600431 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala
@@ -58,7 +58,7 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc
import Dispatchers._
- val cachingConfig = new CachingConfig(settings.config)
+ val cachingConfig: akka.dispatch.CachingConfig = new CachingConfig(settings.config)
val defaultDispatcherConfig: Config =
idConfig(DefaultDispatcherId).withFallback(settings.config.getConfig(DefaultDispatcherId))
@@ -92,7 +92,7 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc
// It doesn't matter if we create a dispatcher configurator that isn't used due to concurrent lookup.
// That shouldn't happen often and in case it does the actual ExecutorService isn't
// created until used, i.e. cheap.
- val newConfigurator =
+ val newConfigurator: akka.dispatch.MessageDispatcherConfigurator =
if (cachingConfig.hasPath(id)) configuratorFrom(config(id))
else throw new ConfigurationException(s"Dispatcher [$id] not configured")
@@ -132,7 +132,7 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc
*/
private[akka] def config(id: String, appConfig: Config): Config = {
import scala.collection.JavaConverters._
- def simpleName = id.substring(id.lastIndexOf('.') + 1)
+ def simpleName: String = id.substring(id.lastIndexOf('.') + 1)
idConfig(id)
.withFallback(appConfig)
.withFallback(ConfigFactory.parseMap(Map("name" → simpleName).asJava))
@@ -180,7 +180,7 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc
classOf[BalancingDispatcherConfigurator].getName)
case "PinnedDispatcher" ⇒ new PinnedDispatcherConfigurator(cfg, prerequisites)
case fqn ⇒
- val args = List(classOf[Config] → cfg, classOf[DispatcherPrerequisites] → prerequisites)
+ val args: List[(Class[_ >: akka.dispatch.DispatcherPrerequisites with com.typesafe.config.Config <: Object], Object)] = List(classOf[Config] → cfg, classOf[DispatcherPrerequisites] → prerequisites)
prerequisites.dynamicAccess.createInstanceFor[MessageDispatcherConfigurator](fqn, args).recover({
case exception ⇒
throw new ConfigurationException(
@@ -235,22 +235,22 @@ class BalancingDispatcherConfigurator(_config: Config, _prerequisites: Dispatche
extends MessageDispatcherConfigurator(BalancingDispatcherConfigurator.amendConfig(_config), _prerequisites) {
private val instance = {
- val mailboxes = prerequisites.mailboxes
- val id = config.getString("id")
- val requirement = mailboxes.getMailboxRequirement(config)
+ val mailboxes: akka.dispatch.Mailboxes = prerequisites.mailboxes
+ val id: String = config.getString("id")
+ val requirement: Class[_ <: AnyRef] = mailboxes.getMailboxRequirement(config)
if (!classOf[MultipleConsumerSemantics].isAssignableFrom(requirement))
throw new IllegalArgumentException(
"BalancingDispatcher must have 'mailbox-requirement' which implements akka.dispatch.MultipleConsumerSemantics; " +
s"dispatcher [$id] has [$requirement]")
- val mailboxType =
+ val mailboxType: akka.dispatch.MailboxType =
if (config.hasPath("mailbox")) {
- val mt = mailboxes.lookup(config.getString("mailbox"))
+ val mt: akka.dispatch.MailboxType = mailboxes.lookup(config.getString("mailbox"))
if (!requirement.isAssignableFrom(mailboxes.getProducedMessageQueueType(mt)))
throw new IllegalArgumentException(
s"BalancingDispatcher [$id] has 'mailbox' [${mt.getClass}] which is incompatible with 'mailbox-requirement' [$requirement]")
mt
} else if (config.hasPath("mailbox-type")) {
- val mt = mailboxes.lookup(id)
+ val mt: akka.dispatch.MailboxType = mailboxes.lookup(id)
if (!requirement.isAssignableFrom(mailboxes.getProducedMessageQueueType(mt)))
throw new IllegalArgumentException(
s"BalancingDispatcher [$id] has 'mailbox-type' [${mt.getClass}] which is incompatible with 'mailbox-requirement' [$requirement]")
diff --git a/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala b/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala
index 510e131..caa8371 100644
--- a/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala
@@ -45,7 +45,7 @@ object ForkJoinExecutorConfigurator {
Thread.currentThread.interrupt()
false
case anything: Throwable ⇒
- val t = Thread.currentThread
+ val t: Thread = Thread.currentThread
t.getUncaughtExceptionHandler match {
case null ⇒
case some ⇒ some.uncaughtException(t, anything)
@@ -72,14 +72,14 @@ class ForkJoinExecutorConfigurator(config: Config, prerequisites: DispatcherPrer
}
final def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = {
- val tf = threadFactory match {
+ val tf: java.util.concurrent.ThreadFactory = threadFactory match {
case m: MonitorableThreadFactory ⇒
// add the dispatcher id to the thread names
m.withName(m.name + "-" + id)
case other ⇒ other
}
- val asyncMode = config.getString("task-peeking-mode") match {
+ val asyncMode: Boolean = config.getString("task-peeking-mode") match {
case "FIFO" ⇒ true
case "LIFO" ⇒ false
case unsupported ⇒ throw new IllegalArgumentException("Cannot instantiate ForkJoinExecutorServiceFactory. " +
diff --git a/akka-actor/src/main/scala/akka/dispatch/Future.scala b/akka-actor/src/main/scala/akka/dispatch/Future.scala
index 2435afb..7eb1627 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Future.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Future.scala
@@ -119,7 +119,7 @@ object Futures {
* Creates an already completed CompletionStage with the specified exception
*/
def failedCompletionStage[T](ex: Throwable): CompletionStage[T] = {
- val f = CompletableFuture.completedFuture[T](null.asInstanceOf[T])
+ val f: java.util.concurrent.CompletableFuture[T] = CompletableFuture.completedFuture[T](null.asInstanceOf[T])
f.obtrudeException(ex)
f
}
@@ -128,7 +128,7 @@ object Futures {
* Returns a Future that will hold the optional result of the first Future with a result that matches the predicate
*/
def find[T <: AnyRef](futures: JIterable[Future[T]], predicate: JFunc[T, java.lang.Boolean], executor: ExecutionContext): Future[JOption[T]] = {
- implicit val ec = executor
+ implicit val ec: scala.concurrent.ExecutionContext = executor
compat.Future.find[T](futures.asScala)(predicate.apply(_))(executor) map JOption.fromScalaOption
}
@@ -158,7 +158,7 @@ object Futures {
* Useful for reducing many Futures into a single Future.
*/
def sequence[A](in: JIterable[Future[A]], executor: ExecutionContext): Future[JIterable[A]] = {
- implicit val d = executor
+ implicit val d: scala.concurrent.ExecutionContext = executor
in.asScala.foldLeft(Future(new JLinkedList[A]())) { (fr, fa) ⇒ for (r ← fr; a ← fa) yield { r add a; r } }
}
@@ -168,9 +168,9 @@ object Futures {
* in parallel.
*/
def traverse[A, B](in: JIterable[A], fn: JFunc[A, Future[B]], executor: ExecutionContext): Future[JIterable[B]] = {
- implicit val d = executor
+ implicit val d: scala.concurrent.ExecutionContext = executor
in.asScala.foldLeft(Future(new JLinkedList[B]())) { (fr, a) ⇒
- val fb = fn(a)
+ val fb: scala.concurrent.Future[B] = fn(a)
for (r ← fr; b ← fb) yield { r add b; r }
}
}
@@ -222,7 +222,7 @@ object japi {
* Java API
*/
abstract class OnSuccess[-T] extends japi.CallbackBridge[T] {
- protected final override def internal(result: T) = onSuccess(result)
+ protected final override def internal(result: T): Unit = onSuccess(result)
/**
* This method will be invoked once when/if a Future that this callback is registered on
@@ -239,7 +239,7 @@ abstract class OnSuccess[-T] extends japi.CallbackBridge[T] {
* Java API
*/
abstract class OnFailure extends japi.CallbackBridge[Throwable] {
- protected final override def internal(failure: Throwable) = onFailure(failure)
+ protected final override def internal(failure: Throwable): Unit = onFailure(failure)
/**
* This method will be invoked once when/if a Future that this callback is registered on
diff --git a/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala b/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala
index cc884e2..1ab0df9 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala
@@ -38,8 +38,8 @@ private[akka] object Mailbox {
final val Scheduled = 2 // Deliberately without type ascription to make it a compile-time constant
// Shifted by 2: the suspend count!
final val shouldScheduleMask = 3
- final val shouldNotProcessMask = ~2
- final val suspendMask = ~3
+ final val shouldNotProcessMask: Int = ~2
+ final val suspendMask: Int = ~3
final val suspendUnit = 4
// mailbox debugging helper using println (see below)
@@ -144,7 +144,7 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
case Closed ⇒
setStatus(Closed); false
case s ⇒
- val next = if (s < suspendUnit) s else s - suspendUnit
+ val next: akka.dispatch.Mailbox.Status = if (s < suspendUnit) s else s - suspendUnit
if (updateStatus(s, next)) next < suspendUnit
else resume()
}
@@ -180,7 +180,7 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
*/
@tailrec
final def setAsScheduled(): Boolean = {
- val s = currentStatus
+ val s: akka.dispatch.Mailbox.Status = currentStatus
/*
* Only try to add Scheduled bit if pure Open/Suspended, not Closed or with
* Scheduled bit already set.
@@ -194,7 +194,7 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
*/
@tailrec
final def setAsIdle(): Boolean = {
- val s = currentStatus
+ val s: akka.dispatch.Mailbox.Status = currentStatus
updateStatus(s, s & ~Scheduled) || setAsIdle()
}
/*
@@ -236,7 +236,7 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
Thread.currentThread.interrupt()
false
case anything: Throwable ⇒
- val t = Thread.currentThread
+ val t: Thread = Thread.currentThread
t.getUncaughtExceptionHandler match {
case null ⇒
case some ⇒ some.uncaughtException(t, anything)
@@ -251,7 +251,7 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
left: Int = java.lang.Math.max(dispatcher.throughput, 1),
deadlineNs: Long = if (dispatcher.isThroughputDeadlineTimeDefined == true) System.nanoTime + dispatcher.throughputDeadlineTime.toNanos else 0L): Unit =
if (shouldProcessMessage) {
- val next = dequeue()
+ val next: akka.dispatch.Envelope = dequeue()
if (next ne null) {
if (Mailbox.debug) println(actor.self + " processing message " + next)
actor invoke next
@@ -274,7 +274,7 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
var interruption: Throwable = null
var messageList = systemDrain(SystemMessageList.LNil)
while ((messageList.nonEmpty) && !isClosed) {
- val msg = messageList.head
+ val msg: akka.dispatch.sysmsg.SystemMessage = messageList.head
messageList = messageList.tail
msg.unlink()
if (debug) println(actor.self + " processing system message " + msg + " with " + actor.childrenRefs)
@@ -289,9 +289,9 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
* if we closed the mailbox, we must dump the remaining system messages
* to deadLetters (this is essential for DeathWatch)
*/
- val dlm = actor.dispatcher.mailboxes.deadLetterMailbox
+ val dlm: akka.dispatch.Mailbox = actor.dispatcher.mailboxes.deadLetterMailbox
while (messageList.nonEmpty) {
- val msg = messageList.head
+ val msg: akka.dispatch.sysmsg.SystemMessage = messageList.head
messageList = messageList.tail
msg.unlink()
try dlm.systemEnqueue(actor.self, msg)
@@ -315,11 +315,11 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
*/
protected[dispatch] def cleanUp(): Unit =
if (actor ne null) { // actor is null for the deadLetterMailbox
- val dlm = actor.dispatcher.mailboxes.deadLetterMailbox
+ val dlm: akka.dispatch.Mailbox = actor.dispatcher.mailboxes.deadLetterMailbox
var messageList = systemDrain(new LatestFirstSystemMessageList(NoMessage))
while (messageList.nonEmpty) {
// message must be “virgin” before being able to systemEnqueue again
- val msg = messageList.head
+ val msg: akka.dispatch.sysmsg.SystemMessage = messageList.head
messageList = messageList.tail
msg.unlink()
dlm.systemEnqueue(actor.self, msg)
@@ -378,7 +378,7 @@ class NodeMessageQueue extends AbstractNodeQueue[Envelope] with MessageQueue wit
final def hasMessages: Boolean = !isEmpty()
@tailrec final def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = {
- val envelope = dequeue()
+ val envelope: akka.dispatch.Envelope = dequeue()
if (envelope ne null) {
deadLetters.enqueue(owner, envelope)
cleanUp(owner, deadLetters)
@@ -406,7 +406,7 @@ class BoundedNodeMessageQueue(capacity: Int) extends AbstractBoundedNodeQueue[En
final def hasMessages: Boolean = !isEmpty()
@tailrec final def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = {
- val envelope = dequeue()
+ val envelope: akka.dispatch.Envelope = dequeue()
if (envelope ne null) {
deadLetters.enqueue(owner, envelope)
cleanUp(owner, deadLetters)
@@ -440,7 +440,7 @@ private[akka] trait DefaultSystemMessageQueue { self: Mailbox ⇒
final def systemEnqueue(receiver: ActorRef, message: SystemMessage): Unit = {
assert(message.unlinked)
if (Mailbox.debug) println(receiver + " having enqueued " + message)
- val currentList = systemQueueGet
+ val currentList: akka.dispatch.sysmsg.LatestFirstSystemMessageList = systemQueueGet
if (currentList.head == NoMessage) {
if (actor ne null) actor.dispatcher.mailboxes.deadLetterMailbox.systemEnqueue(receiver, message)
} else {
@@ -453,7 +453,7 @@ private[akka] trait DefaultSystemMessageQueue { self: Mailbox ⇒
@tailrec
final def systemDrain(newContents: LatestFirstSystemMessageList): EarliestFirstSystemMessageList = {
- val currentList = systemQueueGet
+ val currentList: akka.dispatch.sysmsg.LatestFirstSystemMessageList = systemQueueGet
if (currentList.head == NoMessage) new EarliestFirstSystemMessageList(null)
else if (systemQueuePut(currentList, newContents)) currentList.reverse
else systemDrain(newContents)
@@ -477,8 +477,8 @@ trait MultipleConsumerSemantics
*/
trait QueueBasedMessageQueue extends MessageQueue with MultipleConsumerSemantics {
def queue: Queue[Envelope]
- def numberOfMessages = queue.size
- def hasMessages = !queue.isEmpty
+ def numberOfMessages: Int = queue.size
+ def hasMessages: Boolean = !queue.isEmpty
def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = {
if (hasMessages) {
var envelope = dequeue
@@ -772,7 +772,7 @@ final case class UnboundedDequeBasedMailbox() extends MailboxType with ProducesM
object UnboundedDequeBasedMailbox {
class MessageQueue extends LinkedBlockingDeque[Envelope] with UnboundedDequeBasedMessageQueue {
- final val queue = this
+ final val queue: akka.dispatch.UnboundedDequeBasedMailbox.MessageQueue = this
}
}
@@ -797,7 +797,7 @@ case class BoundedDequeBasedMailbox( final val capacity: Int, override final val
object BoundedDequeBasedMailbox {
class MessageQueue(capacity: Int, val pushTimeOut: FiniteDuration)
extends LinkedBlockingDeque[Envelope](capacity) with BoundedDequeBasedMessageQueue {
- final val queue = this
+ final val queue: akka.dispatch.BoundedDequeBasedMailbox.MessageQueue = this
}
}
@@ -814,7 +814,7 @@ trait ControlAwareMessageQueueSemantics extends QueueBasedMessageQueue {
}
def dequeue(): Envelope = {
- val controlMsg = controlQueue.poll()
+ val controlMsg: akka.dispatch.Envelope = controlQueue.poll()
if (controlMsg ne null) controlMsg
else queue.poll()
@@ -875,8 +875,8 @@ object BoundedControlAwareMailbox {
private final val notFull = putLock.newCondition()
// no need to use blocking queues here, as blocking is being handled in `enqueueWithTimeout`
- val controlQueue = new ConcurrentLinkedQueue[Envelope]()
- val queue = new ConcurrentLinkedQueue[Envelope]()
+ val controlQueue: java.util.concurrent.ConcurrentLinkedQueue[akka.dispatch.Envelope] = new ConcurrentLinkedQueue[Envelope]()
+ val queue: java.util.concurrent.ConcurrentLinkedQueue[akka.dispatch.Envelope] = new ConcurrentLinkedQueue[Envelope]()
override def enqueue(receiver: ActorRef, handle: Envelope): Unit = handle match {
case envelope @ Envelope(_: ControlMessage, _) ⇒ enqueueWithTimeout(controlQueue, receiver, envelope)
@@ -888,14 +888,14 @@ object BoundedControlAwareMailbox {
@tailrec
final override def dequeue(): Envelope = {
- val count = size.get()
+ val count: Int = size.get()
// if both queues are empty return null
if (count > 0) {
// if there are messages try to fetch the current head
// or retry if other consumer dequeued in the mean time
if (size.compareAndSet(count, count - 1)) {
- val item = super.dequeue()
+ val item: akka.dispatch.Envelope = super.dequeue()
if (size.get < capacity) signalNotFull()
@@ -922,7 +922,7 @@ object BoundedControlAwareMailbox {
var remaining = pushTimeOut.toNanos
putLock.lockInterruptibly()
- val inserted = try {
+ val inserted: Boolean = try {
var stop = false
while (size.get() == capacity && !stop) {
remaining = notFull.awaitNanos(remaining)
@@ -933,7 +933,7 @@ object BoundedControlAwareMailbox {
false
} else {
q.add(envelope)
- val c = size.incrementAndGet()
+ val c: Int = size.incrementAndGet()
if (c < capacity) notFull.signal()
diff --git a/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala b/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala
index 7092c88..7d363dd 100644
--- a/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala
@@ -90,13 +90,13 @@ private[akka] class Mailboxes(
private var mailboxSizeWarningIssued = false
private var mailboxNonZeroPushTimeoutWarningIssued = false
- def getMailboxRequirement(config: Config) = config.getString("mailbox-requirement") match {
+ def getMailboxRequirement(config: Config): Class[_ <: AnyRef] = config.getString("mailbox-requirement") match {
case NoMailboxRequirement ⇒ classOf[MessageQueue]
case x ⇒ dynamicAccess.getClassFor[AnyRef](x).get
}
def getProducedMessageQueueType(mailboxType: MailboxType): Class[_] = {
- val pmqClass = classOf[ProducesMessageQueue[_]]
+ val pmqClass: Class[akka.dispatch.ProducesMessageQueue[_]] = classOf[ProducesMessageQueue[_]]
if (!pmqClass.isAssignableFrom(mailboxType.getClass)) classOf[MessageQueue]
else Reflect.findMarker(mailboxType.getClass, pmqClass) match {
case t: ParameterizedType ⇒
@@ -112,16 +112,16 @@ private[akka] class Mailboxes(
* Finds out the mailbox type for an actor based on configuration, props and requirements.
*/
protected[akka] def getMailboxType(props: Props, dispatcherConfig: Config): MailboxType = {
- val id = dispatcherConfig.getString("id")
- val deploy = props.deploy
- val actorClass = props.actorClass
- lazy val actorRequirement = getRequiredType(actorClass)
+ val id: String = dispatcherConfig.getString("id")
+ val deploy: akka.actor.Deploy = props.deploy
+ val actorClass: Class[_ <: akka.actor.Actor] = props.actorClass
+ lazy val actorRequirement: Class[_] = getRequiredType(actorClass)
val mailboxRequirement: Class[_] = getMailboxRequirement(dispatcherConfig)
val hasMailboxRequirement: Boolean = mailboxRequirement != classOf[MessageQueue]
- val hasMailboxType =
+ val hasMailboxType: Boolean =
dispatcherConfig.hasPath("mailbox-type") &&
dispatcherConfig.getString("mailbox-type") != Deploy.NoMailboxGiven
@@ -176,18 +176,18 @@ private[akka] class Mailboxes(
mailboxTypeConfigurators.get(id) match {
case null ⇒
// It doesn't matter if we create a mailbox type configurator that isn't used due to concurrent lookup.
- val newConfigurator = id match {
+ val newConfigurator: akka.dispatch.MailboxType = id match {
// TODO RK remove these two for Akka 2.3
case "unbounded" ⇒ UnboundedMailbox()
case "bounded" ⇒ new BoundedMailbox(settings, config(id))
case _ ⇒
if (!settings.config.hasPath(id)) throw new ConfigurationException(s"Mailbox Type [${id}] not configured")
- val conf = config(id)
+ val conf: com.typesafe.config.Config = config(id)
- val mailboxType = conf.getString("mailbox-type") match {
+ val mailboxType: akka.dispatch.MailboxType = conf.getString("mailbox-type") match {
case "" ⇒ throw new ConfigurationException(s"The setting mailbox-type, defined in [$id] is empty")
case fqcn ⇒
- val args = List(classOf[ActorSystem.Settings] → settings, classOf[Config] → conf)
+ val args: List[(Class[_ >: com.typesafe.config.Config with akka.actor.ActorSystem.Settings <: Object], Object)] = List(classOf[ActorSystem.Settings] → settings, classOf[Config] → conf)
dynamicAccess.createInstanceFor[MailboxType](fqcn, args).recover({
case exception ⇒
throw new IllegalArgumentException(
@@ -250,12 +250,12 @@ private[akka] class Mailboxes(
if (dispatcher == Dispatchers.DefaultDispatcherId && mailbox == Mailboxes.DefaultMailboxId)
defaultStashCapacity
else {
- val cache = stashCapacityCache.get
- val key = dispatcher + "-" + mailbox
+ val cache: Map[String, Int] = stashCapacityCache.get
+ val key: String = dispatcher + "-" + mailbox
cache.get(key) match {
case Some(value) ⇒ value
case None ⇒
- val value = stashCapacityFromConfig(dispatcher, mailbox)
+ val value: Int = stashCapacityFromConfig(dispatcher, mailbox)
updateCache(cache, key, value)
value
}
@@ -263,9 +263,9 @@ private[akka] class Mailboxes(
}
private def stashCapacityFromConfig(dispatcher: String, mailbox: String): Int = {
- val disp = settings.config.getConfig(dispatcher)
- val fallback = disp.withFallback(settings.config.getConfig(Mailboxes.DefaultMailboxId))
- val config =
+ val disp: com.typesafe.config.Config = settings.config.getConfig(dispatcher)
+ val fallback: com.typesafe.config.Config = disp.withFallback(settings.config.getConfig(Mailboxes.DefaultMailboxId))
+ val config: com.typesafe.config.Config =
if (mailbox == Mailboxes.DefaultMailboxId) fallback
else settings.config.getConfig(mailbox).withFallback(fallback)
config.getInt("stash-capacity")
diff --git a/akka-actor/src/main/scala/akka/dispatch/PinnedDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/PinnedDispatcher.scala
index 599152a..4771ad4 100644
--- a/akka-actor/src/main/scala/akka/dispatch/PinnedDispatcher.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/PinnedDispatcher.scala
@@ -32,14 +32,14 @@ class PinnedDispatcher(
private var owner: ActorCell = _actor
//Relies on an external lock provided by MessageDispatcher.attach
- protected[akka] override def register(actorCell: ActorCell) = {
- val actor = owner
+ protected[akka] override def register(actorCell: ActorCell): Unit = {
+ val actor: akka.actor.ActorCell = owner
if ((actor ne null) && actorCell != actor) throw new IllegalArgumentException("Cannot register to anyone but " + actor)
owner = actorCell
super.register(actorCell)
}
//Relies on an external lock provided by MessageDispatcher.detach
- protected[akka] override def unregister(actor: ActorCell) = {
+ protected[akka] override def unregister(actor: ActorCell): Unit = {
super.unregister(actor)
owner = null
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala
index 41e8908..c19d837 100644
--- a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala
@@ -90,7 +90,7 @@ final case class ThreadPoolConfig(
}
}
final def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = {
- val tf = threadFactory match {
+ val tf: java.util.concurrent.ThreadFactory = threadFactory match {
case m: MonitorableThreadFactory ⇒
// add the dispatcher id to the thread names
m.withName(m.name + "-" + id)
@@ -161,13 +161,13 @@ object MonitorableThreadFactory {
private[akka] class AkkaForkJoinWorkerThread(_pool: ForkJoinPool) extends ForkJoinWorkerThread(_pool) with BlockContext {
override def blockOn[T](thunk: ⇒ T)(implicit permission: CanAwait): T = {
- val result = new AtomicReference[Option[T]](None)
+ val result: java.util.concurrent.atomic.AtomicReference[Option[T]] = new AtomicReference[Option[T]](None)
ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker {
def block(): Boolean = {
result.set(Some(thunk))
true
}
- def isReleasable = result.get.isDefined
+ def isReleasable: Boolean = result.get.isDefined
})
result.get.get // Exception intended if None
}
@@ -183,7 +183,7 @@ final case class MonitorableThreadFactory(
extends ThreadFactory with ForkJoinPool.ForkJoinWorkerThreadFactory {
def newThread(pool: ForkJoinPool): ForkJoinWorkerThread = {
- val t = wire(new MonitorableThreadFactory.AkkaForkJoinWorkerThread(pool))
+ val t: akka.dispatch.MonitorableThreadFactory.AkkaForkJoinWorkerThread = wire(new MonitorableThreadFactory.AkkaForkJoinWorkerThread(pool))
// Name of the threads for the ForkJoinPool are not customizable. Change it here.
t.setName(name + "-" + counter.incrementAndGet())
t
@@ -208,31 +208,31 @@ trait ExecutorServiceDelegate extends ExecutorService {
def executor: ExecutorService
- def execute(command: Runnable) = executor.execute(command)
+ def execute(command: Runnable): Unit = executor.execute(command)
def shutdown() { executor.shutdown() }
- def shutdownNow() = executor.shutdownNow()
+ def shutdownNow(): java.util.List[Runnable] = executor.shutdownNow()
- def isShutdown = executor.isShutdown
+ def isShutdown: Boolean = executor.isShutdown
- def isTerminated = executor.isTerminated
+ def isTerminated: Boolean = executor.isTerminated
- def awaitTermination(l: Long, timeUnit: TimeUnit) = executor.awaitTermination(l, timeUnit)
+ def awaitTermination(l: Long, timeUnit: TimeUnit): Boolean = executor.awaitTermination(l, timeUnit)
- def submit[T](callable: Callable[T]) = executor.submit(callable)
+ def submit[T](callable: Callable[T]): java.util.concurrent.Future[T] = executor.submit(callable)
- def submit[T](runnable: Runnable, t: T) = executor.submit(runnable, t)
+ def submit[T](runnable: Runnable, t: T): java.util.concurrent.Future[T] = executor.submit(runnable, t)
- def submit(runnable: Runnable) = executor.submit(runnable)
+ def submit(runnable: Runnable): java.util.concurrent.Future[_] = executor.submit(runnable)
- def invokeAll[T](callables: Collection[_ <: Callable[T]]) = executor.invokeAll(callables)
+ def invokeAll[T](callables: Collection[_ <: Callable[T]]): java.util.List[java.util.concurrent.Future[T]] = executor.invokeAll(callables)
- def invokeAll[T](callables: Collection[_ <: Callable[T]], l: Long, timeUnit: TimeUnit) = executor.invokeAll(callables, l, timeUnit)
+ def invokeAll[T](callables: Collection[_ <: Callable[T]], l: Long, timeUnit: TimeUnit): java.util.List[java.util.concurrent.Future[T]] = executor.invokeAll(callables, l, timeUnit)
- def invokeAny[T](callables: Collection[_ <: Callable[T]]) = executor.invokeAny(callables)
+ def invokeAny[T](callables: Collection[_ <: Callable[T]]): T = executor.invokeAny(callables)
- def invokeAny[T](callables: Collection[_ <: Callable[T]], l: Long, timeUnit: TimeUnit) = executor.invokeAny(callables, l, timeUnit)
+ def invokeAny[T](callables: Collection[_ <: Callable[T]], l: Long, timeUnit: TimeUnit): T = executor.invokeAny(callables, l, timeUnit)
}
/**
diff --git a/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala b/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala
index a53019d..e8b38aa 100644
--- a/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala
@@ -82,18 +82,18 @@ private[akka] class AffinityPool(
private def getQueueForRunnable(command: Runnable) = {
- val runnableHash = command.hashCode()
+ val runnableHash: Int = command.hashCode()
- def sbhash(i: Int) = reverseBytes(i * 0x9e3775cd) * 0x9e3775cd
+ def sbhash(i: Int): Int = reverseBytes(i * 0x9e3775cd) * 0x9e3775cd
- def getNext = executionCounter.incrementAndGet() % parallelism
+ def getNext: Int = executionCounter.incrementAndGet() % parallelism
def updateIfAbsentAndGetQueueIndex(
workerQueueIndex: AtomicReference[ImmutableIntMap],
runnableHash: Int, queueIndex: ⇒ Int): Int = {
@tailrec
def updateIndex(): Unit = {
- val prev = workerQueueIndex.get()
+ val prev: akka.util.ImmutableIntMap = workerQueueIndex.get()
if (!runnableToWorkerQueueIndex.compareAndSet(prev, prev.updateIfAbsent(runnableHash, queueIndex))) {
updateIndex()
}
@@ -102,7 +102,7 @@ private[akka] class AffinityPool(
workerQueueIndex.get().get(runnableHash) // can safely call get..
}
- val workQueueIndex =
+ val workQueueIndex: Int =
if (fairDistributionThreshold == 0 || runnableToWorkerQueueIndex.get().size > fairDistributionThreshold)
Math.abs(sbhash(runnableHash)) % parallelism
else
@@ -118,7 +118,7 @@ private[akka] class AffinityPool(
private def addWorker(workers: mutable.Set[ThreadPoolWorker], q: BoundedTaskQueue): Unit = {
locked(bookKeepingLock) {
- val worker = new ThreadPoolWorker(q, new IdleStrategy(idleCpuLevel))
+ val worker: AffinityPool.this.ThreadPoolWorker = new ThreadPoolWorker(q, new IdleStrategy(idleCpuLevel))
workers.add(worker)
worker.startWorker()
}
@@ -330,7 +330,7 @@ private[akka] class AffinityPool(
*
* 3) We are not in ShutDown state (in which we should not be processing any enqueued tasks)
*/
- def shouldKeepRunning =
+ def shouldKeepRunning: Boolean =
(poolState < ShuttingDown || !q.isEmpty) &&
!Thread.interrupted() &&
poolState != ShutDown
@@ -338,7 +338,7 @@ private[akka] class AffinityPool(
var abruptTermination = true
try {
while (shouldKeepRunning) {
- val c = q.poll()
+ val c: Runnable = q.poll()
if (c ne null) {
runCommand(c)
idleStrategy.reset()
@@ -351,11 +351,11 @@ private[akka] class AffinityPool(
}
}
- def stop() =
+ def stop(): Unit =
if (!thread.isInterrupted && workerState != NotStarted)
thread.interrupt()
- def stopIfIdle() =
+ def stopIfIdle(): Unit =
if (workerState == Idle)
stop()
}
diff --git a/akka-actor/src/main/scala/akka/dispatch/sysmsg/SystemMessage.scala b/akka-actor/src/main/scala/akka/dispatch/sysmsg/SystemMessage.scala
index e32b2c5..0fc2fac 100644
--- a/akka-actor/src/main/scala/akka/dispatch/sysmsg/SystemMessage.scala
+++ b/akka-actor/src/main/scala/akka/dispatch/sysmsg/SystemMessage.scala
@@ -23,7 +23,7 @@ private[akka] object SystemMessageList {
@tailrec
private[sysmsg] def reverseInner(head: SystemMessage, acc: SystemMessage): SystemMessage = {
if (head eq null) acc else {
- val next = head.next
+ val next: akka.dispatch.sysmsg.SystemMessage = head.next
head.next = acc
reverseInner(next, head)
}
@@ -161,7 +161,7 @@ private[akka] class EarliestFirstSystemMessageList(val head: SystemMessage) exte
var remaining = other
var result = this
while (remaining.nonEmpty) {
- val msg = remaining.head
+ val msg: akka.dispatch.sysmsg.SystemMessage = remaining.head
remaining = remaining.tail
result ::= msg
}
diff --git a/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala b/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala
index be76cc7..1a0cf71 100644
--- a/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala
+++ b/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala
@@ -24,7 +24,7 @@ protected[akka] class ActorClassificationUnsubscriber(bus: ManagedActorClassific
if (debug) context.system.eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"will monitor $bus"))
}
- def receive = {
+ def receive: PartialFunction[Any, Unit] = {
case Register(actor, seq) if seq == nextSeq ⇒
if (debug) context.system.eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"registered watch for $actor in $bus"))
context watch actor
@@ -64,8 +64,8 @@ private[akka] object ActorClassificationUnsubscriber {
final case class Register(actor: ActorRef, seq: Int)
final case class Unregister(actor: ActorRef, seq: Int)
- def start(system: ActorSystem, bus: ManagedActorClassification, debug: Boolean = false) = {
- val debug = system.settings.config.getBoolean("akka.actor.debug.event-stream")
+ def start(system: ActorSystem, bus: ManagedActorClassification, debug: Boolean = false): akka.actor.ActorRef = {
+ val debug: Boolean = system.settings.config.getBoolean("akka.actor.debug.event-stream")
system.asInstanceOf[ExtendedActorSystem]
.systemActorOf(props(bus, debug), "actorClassificationUnsubscriber-" + unsubscribersCount.incrementAndGet())
}
diff --git a/akka-actor/src/main/scala/akka/event/AddressTerminatedTopic.scala b/akka-actor/src/main/scala/akka/event/AddressTerminatedTopic.scala
index cce9319..3556bed 100644
--- a/akka-actor/src/main/scala/akka/event/AddressTerminatedTopic.scala
+++ b/akka-actor/src/main/scala/akka/event/AddressTerminatedTopic.scala
@@ -24,7 +24,7 @@ import akka.actor.ExtensionIdProvider
private[akka] object AddressTerminatedTopic extends ExtensionId[AddressTerminatedTopic] with ExtensionIdProvider {
override def get(system: ActorSystem): AddressTerminatedTopic = super.get(system)
- override def lookup = AddressTerminatedTopic
+ override def lookup: akka.event.AddressTerminatedTopic.type = AddressTerminatedTopic
override def createExtension(system: ExtendedActorSystem): AddressTerminatedTopic =
new AddressTerminatedTopic
@@ -38,13 +38,13 @@ private[akka] final class AddressTerminatedTopic extends Extension {
private val subscribers = new AtomicReference[Set[ActorRef]](Set.empty[ActorRef])
@tailrec def subscribe(subscriber: ActorRef): Unit = {
- val current = subscribers.get
+ val current: Set[akka.actor.ActorRef] = subscribers.get
if (!subscribers.compareAndSet(current, current + subscriber))
subscribe(subscriber) // retry
}
@tailrec def unsubscribe(subscriber: ActorRef): Unit = {
- val current = subscribers.get
+ val current: Set[akka.actor.ActorRef] = subscribers.get
if (!subscr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment