format source with scalafmt, #2

This commit is contained in:
Auto Format 2022-11-03 09:46:22 +01:00 committed by Matthew de Detrich
parent 0e876025e8
commit 15b163da74
980 changed files with 8776 additions and 8578 deletions

View file

@ -130,7 +130,7 @@ import akka.annotation.InternalApi
// this is backward compatible with the old behaviour, hence it uses the loader used to load the test-kit
// which is not necessarily the one used to load the tests...
// hence this might not include reference config related to the actually executing test
//todo: might be better NOT to pass any class loader and let typesafeConfig rely on the contextClassLoader
// todo: might be better NOT to pass any class loader and let typesafeConfig rely on the contextClassLoader
// (which is usually the system class loader)
def defaultReference: Config = ConfigFactory.defaultReference(getClass.getClassLoader)
}

View file

@ -137,11 +137,11 @@ private[akka] final class BehaviorTestKitImpl[T](
try {
context.setCurrentActorThread()
try {
//we need this to handle message adapters related messages
// we need this to handle message adapters related messages
val intercepted = BehaviorTestKitImpl.Interceptor.inteceptBehaviour(current, context)
currentUncanonical = Behavior.interpretMessage(intercepted, context, message)
//notice we pass current and not intercepted, this way Behaviors.same will be resolved to current which will be intercepted again on the next message
//otherwise we would have risked intercepting an already intercepted behavior (or would have had to explicitly check if the current behavior is already intercepted by us)
// notice we pass current and not intercepted, this way Behaviors.same will be resolved to current which will be intercepted again on the next message
// otherwise we would have risked intercepting an already intercepted behavior (or would have had to explicitly check if the current behavior is already intercepted by us)
current = Behavior.canonicalize(currentUncanonical, current, context)
} finally {
context.clearCurrentActorThread()

View file

@ -166,7 +166,8 @@ private[akka] final class FunctionRef[-T](override val path: ActorPath, send: (T
val i = new BehaviorTestKitImpl[U](system, p, BehaviorImpl.ignore)
_children += p.name -> i
new FunctionRef[U](p, (message, _) => {
new FunctionRef[U](p,
(message, _) => {
val m = f(message);
if (m != null) {
selfInbox.ref ! m; i.selfInbox().ref ! message

View file

@ -134,7 +134,8 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_])
val prevEnd = end
end = start + maxDiff
val ret = try f
val ret =
try f
finally end = prevEnd
val diff = now - start

View file

@ -21,7 +21,6 @@ package object scaladsl {
*
* Uses the scaling factor from the `TestTimeFactor` in the [[TestKitSettings]]
* (in implicit scope).
*
*/
implicit class TestDuration(val duration: FiniteDuration) extends AnyVal {
def dilated(implicit settings: TestKitSettings): FiniteDuration = settings.dilated(duration)

View file

@ -456,7 +456,7 @@ class BehaviorTestKitSpec extends AnyWordSpec with Matchers with LogCapturing {
testkit.expectEffectPF {
case Effect.Spawned(_, "child", _) =>
}
//no effect since the timer's mode was single, hence removed after fired
// no effect since the timer's mode was single, hence removed after fired
send()
testkit.selfInbox().hasMessages should be(false)
}
@ -485,7 +485,7 @@ class BehaviorTestKitSpec extends AnyWordSpec with Matchers with LogCapturing {
testkit.expectEffect {
Effect.Stopped("child")
}
//when scheduling with fixed rate the timer remains scheduled
// when scheduling with fixed rate the timer remains scheduled
send()
testkit.runOne()
testkit.expectEffectPF {

View file

@ -67,11 +67,11 @@ class TestAppenderSpec
"only filter events for given logger name" in {
val count = new AtomicInteger
LoggingTestKit
.custom({
.custom {
case logEvent =>
count.incrementAndGet()
logEvent.message == "Hello from right logger" && logEvent.loggerName == classOf[AnotherLoggerClass].getName
})
}
.withOccurrences(2)
.withLoggerName(classOf[AnotherLoggerClass].getName)
.expect {

View file

@ -22,9 +22,9 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
probe.fishForMessage(shortDuration) {
case _ => FishingOutcomes.complete
}
probe.awaitAssert({
probe.awaitAssert {
"result"
})
}
probe.expectMessageType[String]
probe.expectMessage("whoa")
probe.expectNoMessage()

View file

@ -27,7 +27,7 @@ import scala.util.Success
import scala.util.Try
object AsyncTestingExampleSpec {
//#under-test
// #under-test
object Echo {
case class Ping(message: String, response: ActorRef[Pong])
case class Pong(message: String)
@ -38,9 +38,9 @@ object AsyncTestingExampleSpec {
Behaviors.same
}
}
//#under-test
// #under-test
//#under-test-2
// #under-test-2
case class Message(i: Int, replyTo: ActorRef[Try[Int]])
class Producer(publisher: ActorRef[Message])(implicit scheduler: Scheduler) {
@ -54,7 +54,7 @@ object AsyncTestingExampleSpec {
}
}
//#under-test-2
// #under-test-2
}
@ -62,29 +62,29 @@ object AsyncTestingExampleSpec {
class AsyncTestingExampleSpec
extends AnyWordSpec
with BeforeAndAfterAll
//#test-header
// #test-header
with LogCapturing
//#test-header
// #test-header
with Matchers {
val testKit = ActorTestKit()
//#test-header
// #test-header
import AsyncTestingExampleSpec._
"A testkit" must {
"support verifying a response" in {
//#test-spawn
// #test-spawn
val pinger = testKit.spawn(Echo(), "ping")
val probe = testKit.createTestProbe[Echo.Pong]()
pinger ! Echo.Ping("hello", probe.ref)
probe.expectMessage(Echo.Pong("hello"))
//#test-spawn
// #test-spawn
}
"support verifying a response - anonymous" in {
//#test-spawn-anonymous
// #test-spawn-anonymous
val pinger = testKit.spawn(Echo())
//#test-spawn-anonymous
// #test-spawn-anonymous
val probe = testKit.createTestProbe[Echo.Pong]()
pinger ! Echo.Ping("hello", probe.ref)
probe.expectMessage(Echo.Pong("hello"))
@ -93,7 +93,7 @@ class AsyncTestingExampleSpec
"be able to stop actors under test" in {
// Will fail with 'name not unique' exception if the first actor is not fully stopped
val probe = testKit.createTestProbe[Echo.Pong]()
//#test-stop-actors
// #test-stop-actors
val pinger1 = testKit.spawn(Echo(), "pinger")
pinger1 ! Echo.Ping("hello", probe.ref)
probe.expectMessage(Echo.Pong("hello"))
@ -104,12 +104,12 @@ class AsyncTestingExampleSpec
pinger2 ! Echo.Ping("hello", probe.ref)
probe.expectMessage(Echo.Pong("hello"))
testKit.stop(pinger2, 10.seconds) // Custom timeout
//#test-stop-actors
// #test-stop-actors
}
"support observing mocked behavior" in {
//#test-observe-mocked-behavior
// #test-observe-mocked-behavior
import testKit._
// simulate the happy path
@ -130,13 +130,13 @@ class AsyncTestingExampleSpec
val msg = probe.expectMessageType[Message]
msg.i shouldBe i
}
//#test-observe-mocked-behavior
// #test-observe-mocked-behavior
}
}
//#test-shutdown
// #test-shutdown
override def afterAll(): Unit = testKit.shutdownTestKit()
//#test-shutdown
// #test-shutdown
//#test-header
}
//#test-header

View file

@ -43,7 +43,7 @@ class ManualTimerExampleSpec
manualTime.expectNoMessageFor(10.seconds, probe)
}
//#manual-scheduling-simple
// #manual-scheduling-simple
"schedule repeated ticks" in {
case object Tick
@ -113,7 +113,7 @@ class ManualTimerExampleSpec
probe.expectMessage(Tock(2))
}
//#manual-scheduling-simple
// #manual-scheduling-simple
}
}
//#manual-scheduling-simple

View file

@ -19,13 +19,13 @@ import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
object SyncTestingExampleSpec {
//#child
// #child
val childActor = Behaviors.receiveMessage[String] { _ =>
Behaviors.same[String]
}
//#child
// #child
//#under-test
// #under-test
object Hello {
sealed trait Command
case object CreateAnonymousChild extends Command
@ -58,7 +58,7 @@ object SyncTestingExampleSpec {
who ! "hello"
Behaviors.same
}
//#under-test
// #under-test
}
object ConfigAware {
@ -89,57 +89,57 @@ class SyncTestingExampleSpec extends AnyWordSpec with Matchers {
"Typed actor synchronous testing" must {
"record spawning" in {
//#test-child
// #test-child
val testKit = BehaviorTestKit(Hello())
testKit.run(Hello.CreateChild("child"))
testKit.expectEffect(Spawned(childActor, "child"))
//#test-child
// #test-child
}
"record spawning anonymous" in {
//#test-anonymous-child
// #test-anonymous-child
val testKit = BehaviorTestKit(Hello())
testKit.run(Hello.CreateAnonymousChild)
testKit.expectEffect(SpawnedAnonymous(childActor))
//#test-anonymous-child
// #test-anonymous-child
}
"record message sends" in {
//#test-message
// #test-message
val testKit = BehaviorTestKit(Hello())
val inbox = TestInbox[String]()
testKit.run(Hello.SayHello(inbox.ref))
inbox.expectMessage("hello")
//#test-message
// #test-message
}
"send a message to a spawned child" in {
//#test-child-message
// #test-child-message
val testKit = BehaviorTestKit(Hello())
testKit.run(Hello.SayHelloToChild("child"))
val childInbox = testKit.childInbox[String]("child")
childInbox.expectMessage("hello")
//#test-child-message
// #test-child-message
}
"send a message to an anonymous spawned child" in {
//#test-child-message-anonymous
// #test-child-message-anonymous
val testKit = BehaviorTestKit(Hello())
testKit.run(Hello.SayHelloToAnonymousChild)
val child = testKit.expectEffectType[SpawnedAnonymous[String]]
val childInbox = testKit.childInbox(child.ref)
childInbox.expectMessage("hello stranger")
//#test-child-message-anonymous
// #test-child-message-anonymous
}
"log a message to the logger" in {
//#test-check-logging
// #test-check-logging
val testKit = BehaviorTestKit(Hello())
val inbox = TestInbox[String]("Inboxer")
testKit.run(Hello.LogAndSayHello(inbox.ref))
testKit.logEntries() shouldBe Seq(CapturedLogEvent(Level.INFO, "Saying hello to Inboxer"))
//#test-check-logging
// #test-check-logging
}
"has access to the provided config" in {

View file

@ -8,24 +8,24 @@ object TestConfigExample {
def illustrateApplicationConfig(): Unit = {
//#default-application-conf
// #default-application-conf
import com.typesafe.config.ConfigFactory
ConfigFactory.load()
//#default-application-conf
// #default-application-conf
//#parse-string
// #parse-string
ConfigFactory.parseString("""
akka.loglevel = DEBUG
akka.log-config-on-start = on
""")
//#parse-string
// #parse-string
//#fallback-application-conf
// #fallback-application-conf
ConfigFactory.parseString("""
akka.loglevel = DEBUG
akka.log-config-on-start = on
""").withFallback(ConfigFactory.load())
//#fallback-application-conf
// #fallback-application-conf
}
}

View file

@ -18,11 +18,11 @@ class AkkaExceptionSpec extends AnyWordSpec with Matchers {
"AkkaException" must {
"have a AkkaException(String msg) constructor to be serialization friendly" in {
//if the call to this method completes, we know what there is at least a single constructor which has
//the expected argument type.
// if the call to this method completes, we know what there is at least a single constructor which has
// the expected argument type.
verify(classOf[AkkaException])
//lets also try it for the exception that triggered this bug to be discovered.
// lets also try it for the exception that triggered this bug to be discovered.
verify(classOf[ActorKilledException])
}
}

View file

@ -159,8 +159,8 @@ class ActorRefSpec extends AkkaSpec("""
EventFilter[ActorInitializationException](occurrences = 1).intercept {
intercept[akka.actor.ActorInitializationException] {
wrap(
result => actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result))))
wrap(result =>
actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result))))
}
contextStackMustBeEmpty()
@ -168,8 +168,8 @@ class ActorRefSpec extends AkkaSpec("""
EventFilter[ActorInitializationException](occurrences = 1).intercept {
intercept[akka.actor.ActorInitializationException] {
wrap(
result => actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result)))))))
wrap(result =>
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result)))))))
}
contextStackMustBeEmpty()
@ -196,8 +196,7 @@ class ActorRefSpec extends AkkaSpec("""
EventFilter[ActorInitializationException](occurrences = 2).intercept {
intercept[akka.actor.ActorInitializationException] {
wrap(
result =>
wrap(result =>
actorOf(Props(new FailingInheritingOuterActor(
actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
}
@ -247,22 +246,21 @@ class ActorRefSpec extends AkkaSpec("""
EventFilter[ActorInitializationException](occurrences = 1).intercept {
intercept[akka.actor.ActorInitializationException] {
wrap(
result =>
wrap(result =>
actorOf(
Props(new OuterActor(actorOf(Props(promiseIntercept({ new InnerActor; new InnerActor })(result)))))))
Props(new OuterActor(actorOf(Props(promiseIntercept { new InnerActor; new InnerActor }(result)))))))
}
contextStackMustBeEmpty()
}
EventFilter[ActorInitializationException](occurrences = 1).intercept {
(intercept[java.lang.IllegalStateException] {
intercept[java.lang.IllegalStateException] {
wrap(result =>
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept {
throw new IllegalStateException("Ur state be b0rked")
})(result)))))))
}).getMessage should ===("Ur state be b0rked")
}(result)))))))
}.getMessage should ===("Ur state be b0rked")
contextStackMustBeEmpty()
}
@ -272,9 +270,9 @@ class ActorRefSpec extends AkkaSpec("""
EventFilter[ActorInitializationException](occurrences = 1, pattern = "/user/failingActor:").intercept {
intercept[java.lang.IllegalStateException] {
wrap(result =>
system.actorOf(Props(promiseIntercept({
system.actorOf(Props(promiseIntercept {
throw new IllegalStateException
})(result)), "failingActor"))
}(result)), "failingActor"))
}
}
}
@ -325,9 +323,9 @@ class ActorRefSpec extends AkkaSpec("""
val in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray))
(intercept[java.lang.IllegalStateException] {
intercept[java.lang.IllegalStateException] {
in.readObject
}).getMessage should ===(
}.getMessage should ===(
"Trying to deserialize a serialized ActorRef without an ActorSystem in scope." +
" Use 'akka.serialization.JavaSerializer.currentSystem.withValue(system) { ... }'")
}
@ -422,8 +420,8 @@ class ActorRefSpec extends AkkaSpec("""
}
}))
val ffive = (ref.ask(5)(timeout)).mapTo[String]
val fnull = (ref.ask(0)(timeout)).mapTo[String]
val ffive = ref.ask(5)(timeout).mapTo[String]
val fnull = ref.ask(0)(timeout).mapTo[String]
ref ! PoisonPill
Await.result(ffive, timeout.duration) should ===("five")
@ -466,8 +464,8 @@ class ActorRefSpec extends AkkaSpec("""
def receive = { case name: String => sender() ! context.child(name).isDefined }
}), "parent")
assert(Await.result((parent ? "child"), timeout.duration) === true)
assert(Await.result((parent ? "whatnot"), timeout.duration) === false)
assert(Await.result(parent ? "child", timeout.duration) === true)
assert(Await.result(parent ? "whatnot", timeout.duration) === false)
}
}
}

View file

@ -49,7 +49,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
val root = sysImpl.lookupRoot
def empty(path: String) =
new EmptyLocalActorRef(sysImpl.provider, path match {
new EmptyLocalActorRef(sysImpl.provider,
path match {
case RelativeActorPath(elems) => sysImpl.lookupRoot.path / elems
case _ => throw new RuntimeException()
}, system.eventStream)
@ -128,7 +129,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
val a2 = system.actorOf(p, name)
a2.path should ===(a1.path)
a2.path.toString should ===(a1.path.toString)
a2 should not be (a1)
a2 should not be a1
a2.toString should not be (a1.toString)
watch(a2)

View file

@ -24,7 +24,7 @@ class ActorTimeoutSpec extends AkkaSpec {
"use implicitly supplied timeout" in {
implicit val timeout = Timeout(testTimeout)
val echo = system.actorOf(Props.empty)
val f = (echo ? "hallo")
val f = echo ? "hallo"
intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) }
}

View file

@ -28,11 +28,11 @@ object ConsistencySpec {
}
}
"""
class CacheMisaligned(var value: Long, var padding1: Long, var padding2: Long, var padding3: Int) //Vars, no final fences
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 = new CacheMisaligned(42, 0, 0, 0) // var
var right = new CacheMisaligned(0, 0, 0, 0) // var
var lastStep = -1L
def receive = {
case step: Long =>

View file

@ -79,7 +79,8 @@ class CoordinatedShutdownSpec
// a, b can be in any order
result2.toSet should ===(Set("a", "b", "c"))
checkTopologicalSort(Map("b" -> phase("a"), "c" -> phase("b"), "d" -> phase("b", "c"), "e" -> phase("d"))) should ===(
checkTopologicalSort(Map("b" -> phase("a"), "c" -> phase("b"), "d" -> phase("b", "c"),
"e" -> phase("d"))) should ===(
List("a", "b", "c", "d", "e"))
val result3 =
@ -324,7 +325,8 @@ class CoordinatedShutdownSpec
val shouldBeCancelled = cancellables.zipWithIndex.collect {
case (c, i) if i % 2 == 0 => c
}
val cancelFutures = for {
val cancelFutures =
for {
_ <- cancellables
c <- shouldBeCancelled
} yield Future {
@ -785,7 +787,7 @@ class CoordinatedShutdownSpec
withSystemRunning(newSystem, cs)
TestKit.shutdownActorSystem(newSystem)
shutdownHooks should have size (0)
shutdownHooks should have size 0
protected def myHooksCount: Int = synchronized(shutdownHooks.size)
}

View file

@ -171,7 +171,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout =>
monitor2 ! "ping"
expectMsg("pong") //Needs to be here since watch and unwatch are asynchronous
expectMsg("pong") // Needs to be here since watch and unwatch are asynchronous
terminal ! PoisonPill

View file

@ -47,7 +47,8 @@ class DynamicAccessSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll
}
"try different constructors with recoverWith" in {
instantiateWithDefaultOrStringCtor("akka.actor.TestClassWithStringConstructor").get.name shouldBe "string ctor argument"
instantiateWithDefaultOrStringCtor(
"akka.actor.TestClassWithStringConstructor").get.name shouldBe "string ctor argument"
instantiateWithDefaultOrStringCtor("akka.actor.TestClassWithDefaultConstructor").get.name shouldBe "default"
instantiateWithDefaultOrStringCtor("akka.actor.foo.NonExistingClass") match {
case Failure(t) =>

View file

@ -44,7 +44,7 @@ object FSMActorSpec {
soFar + digit match {
case incomplete if incomplete.length < code.length =>
stay().using(CodeState(incomplete, code))
case codeTry if (codeTry == code) => {
case codeTry if codeTry == code => {
doUnlock()
goto(Open).using(CodeState("", code)).forMax(timeout)
}

View file

@ -25,7 +25,7 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
"be able to become multiple times in its constructor" in {
val a = system.actorOf(Props(new Becomer {
for (i <- 1 to 4) context.become({ case always => sender() ! s"$i:$always" })
for (i <- 1 to 4) context.become { case always => sender() ! s"$i:$always" }
def receive = { case _ => sender() ! "FAILURE" }
}))
a ! "pigdog"
@ -62,7 +62,7 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
val a = system.actorOf(Props(new Actor {
def receive = {
case "init" => sender() ! "init"
case "swap" => context.become({ case x: String => context.sender() ! x })
case "swap" => context.become { case x: String => context.sender() ! x }
}
}))
@ -78,10 +78,10 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
def receive = {
case "init" => sender() ! "init"
case "swap" =>
context.become({
context.become {
case "swapped" => sender() ! "swapped"
case "revert" => context.unbecome()
})
}
}
}))
@ -103,11 +103,11 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender {
def receive = {
case "state" => sender() ! "0"
case "swap" =>
context.become({
context.become {
case "state" => sender() ! "1"
case "swapped" => sender() ! "swapped"
case "crash" => throw new Exception("Crash (expected)!")
})
}
sender() ! "swapped"
}
}))

View file

@ -50,7 +50,7 @@ class ProviderSelectionSpec extends AbstractSpec {
"create a Custom ProviderSelection and set custom provider fqcn in Settings" in {
val other = "other.ActorRefProvider"
val ps = ProviderSelection.Custom(other) //checked by dynamicAccess
val ps = ProviderSelection.Custom(other) // checked by dynamicAccess
ps.fqcn shouldEqual "other.ActorRefProvider"
ps.hasCluster shouldBe false
settingsWith(other).ProviderClass shouldEqual ps.fqcn

View file

@ -240,7 +240,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
"stop continuous scheduling if the task throws exception" taggedAs TimingTest in {
EventFilter[Exception]("TEST", occurrences = 1).intercept {
val count = new AtomicInteger(0)
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis, () => {
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis,
() => {
val c = count.incrementAndGet()
testActor ! c
if (c == 3) throw new RuntimeException("TEST") with NoStackTrace
@ -256,7 +257,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
// when first throws
EventFilter[Exception]("TEST-1", occurrences = 1).intercept {
val count1 = new AtomicInteger(0)
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis, () => {
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis,
() => {
val c = count1.incrementAndGet()
if (c == 1)
throw new IllegalStateException("TEST-1") with NoStackTrace
@ -269,7 +271,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
// when later
EventFilter[Exception]("TEST-3", occurrences = 1).intercept {
val count2 = new AtomicInteger(0)
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis, () => {
collectCancellable(scheduleAdapter.schedule(Duration.Zero, 20.millis,
() => {
val c = count2.incrementAndGet()
testActor ! c
if (c == 3) throw new IllegalStateException("TEST-3") with NoStackTrace
@ -286,7 +289,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
val initialDelay = 200.millis.dilated
val delay = 10.millis.dilated
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay, () => {
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay,
() => {
ticks.incrementAndGet()
}))
Thread.sleep(10.millis.dilated.toMillis)
@ -301,7 +305,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
val initialDelay = 90.millis.dilated
val delay = 500.millis.dilated
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay, () => {
val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay,
() => {
ticks.incrementAndGet()
}))
Thread.sleep((initialDelay + 200.millis.dilated).toMillis)
@ -473,7 +478,8 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
val counter = new AtomicInteger
val terminated = Future {
var rounds = 0
while (Try(sched.scheduleOnce(Duration.Zero, new Scheduler.TaskRunOnClose {
while (Try(sched.scheduleOnce(Duration.Zero,
new Scheduler.TaskRunOnClose {
override def run(): Unit = ()
})(localEC)).isSuccess) {
Thread.sleep(1)
@ -485,7 +491,8 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
def delay = if (ThreadLocalRandom.current.nextBoolean) step * 2 else step
val N = 1000000
(1 to N).foreach(_ =>
sched.scheduleOnce(delay, new Scheduler.TaskRunOnClose {
sched.scheduleOnce(delay,
new Scheduler.TaskRunOnClose {
override def run(): Unit = counter.incrementAndGet()
}))
sched.close()
@ -614,7 +621,8 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
var overrun = headroom
val cap = 1000000
val (success, failure) = Iterator
.continually(Try(sched.scheduleOnce(100.millis, new Scheduler.TaskRunOnClose {
.continually(Try(sched.scheduleOnce(100.millis,
new Scheduler.TaskRunOnClose {
override def run(): Unit = counter.incrementAndGet()
})))
.take(cap)
@ -632,7 +640,8 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev
import system.dispatcher
val counter = new AtomicInteger()
sched.scheduleOnce(10.seconds)(counter.incrementAndGet())
sched.scheduleOnce(10.seconds, new Scheduler.TaskRunOnClose {
sched.scheduleOnce(10.seconds,
new Scheduler.TaskRunOnClose {
override def run(): Unit = counter.incrementAndGet()
})
driver.close()

View file

@ -170,7 +170,7 @@ object SupervisorHierarchySpec {
val sizes = s / kids
var rest = s % kids
val propsTemplate = Props.empty.withDispatcher("hierarchy")
(1 to kids).iterator.map { (id) =>
(1 to kids).iterator.map { id =>
val kidSize = if (rest > 0) {
rest -= 1; sizes + 1
} else sizes
@ -821,7 +821,8 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
"suspend children while failing" taggedAs LongRunningTest in {
val latch = TestLatch()
val slowResumer = system.actorOf(Props(new Actor {
val slowResumer = system.actorOf(
Props(new Actor {
override def supervisorStrategy = OneForOneStrategy() {
case _ => Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume
}

View file

@ -197,7 +197,7 @@ class SupervisorSpec
def kill(pingPongActor: ActorRef) = {
val result = pingPongActor.?(DieReply)(DilatedTimeout)
expectMsg(Timeout, ExceptionMessage) //this is sent from PingPongActor's postRestart()
expectMsg(Timeout, ExceptionMessage) // this is sent from PingPongActor's postRestart()
intercept[RuntimeException] { Await.result(result, DilatedTimeout) }
}
@ -218,7 +218,7 @@ class SupervisorSpec
}
"restart properly when same instance is returned" in {
val restarts = 3 //max number of restarts
val restarts = 3 // max number of restarts
lazy val childInstance = new Actor {
var preRestarts = 0
var postRestarts = 0
@ -439,10 +439,10 @@ class SupervisorSpec
"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()({
override val supervisorStrategy = OneForOneStrategy() {
case e: IllegalStateException if e.getMessage == "OHNOES" => throw e
case _ => SupervisorStrategy.Restart
})
}
val child = context.watch(context.actorOf(Props(new Actor {
override def postRestart(reason: Throwable): Unit = testActor ! "child restarted"
def receive = {
@ -559,7 +559,7 @@ class SupervisorSpec
val pingpong = child(supervisor, Props(new PingPongActor(testActor)))
//impossible to confirm if the restart window is infinite, so making sure maxNrOfRetries is respected correctly
// impossible to confirm if the restart window is infinite, so making sure maxNrOfRetries is respected correctly
kill(pingpong)
kill(pingpong)
kill(pingpong)

View file

@ -21,7 +21,7 @@ class Ticket669Spec extends AkkaSpec with BeforeAndAfterAll with ImplicitSender
// TODO: does this really make sense?
override def atStartup(): Unit = {
Thread.interrupted() //remove interrupted status.
Thread.interrupted() // remove interrupted status.
}
"A supervised actor with lifecycle PERMANENT" should {

View file

@ -177,7 +177,7 @@ object TypedActorSpec {
}
class StackedImpl extends Stacked {
override def stacked: String = "FOOBAR" //Uppercase
override def stacked: String = "FOOBAR" // Uppercase
}
trait LifeCycles {
@ -410,18 +410,18 @@ class TypedActorSpec
t.incr()
t.failingPigdog()
t.read() should ===(1) //Make sure state is not reset after failure
t.read() should ===(1) // Make sure state is not reset after failure
intercept[IllegalStateException] { Await.result(t.failingFuturePigdog(), 2 seconds) }.getMessage should ===(
"expected")
t.read() should ===(1) //Make sure state is not reset after failure
t.read() should ===(1) // Make sure state is not reset after failure
intercept[IllegalStateException] { t.failingJOptionPigdog() }.getMessage should ===("expected")
t.read() should ===(1) //Make sure state is not reset after failure
t.read() should ===(1) // Make sure state is not reset after failure
intercept[IllegalStateException] { t.failingOptionPigdog() }.getMessage should ===("expected")
t.read() should ===(1) //Make sure state is not reset after failure
t.read() should ===(1) // Make sure state is not reset after failure
mustStop(t)
}
@ -559,14 +559,14 @@ class TypedActorSpec
t.crash()
}
//Sneak in a check for the Receiver override
// Sneak in a check for the Receiver override
val ref = ta.getActorRefFor(t)
ref.tell("pigdog", testActor)
expectMsg(timeout.duration, "dogpig")
//Done with that now
// Done with that now
ta.poisonPill(t)
latch.await(10, TimeUnit.SECONDS) should ===(true)

View file

@ -25,7 +25,7 @@ object UidClashTest {
val eventStream: EventStream)
extends MinimalActorRef {
//Ignore everything
// Ignore everything
override def isTerminated: Boolean = true
override def sendSystemMessage(message: SystemMessage): Unit = ()
override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = ()

View file

@ -647,7 +647,7 @@ class BalancingDispatcherModelSpec extends ActorModelSpec(BalancingDispatcherMod
system.stop(a)
system.stop(b)
while (!a.isTerminated && !b.isTerminated) {} //Busy wait for termination
while (!a.isTerminated && !b.isTerminated) {} // Busy wait for termination
assertRefDefaultZero(a)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)
assertRefDefaultZero(b)(registers = 1, unregisters = 1, msgsReceived = 1, msgsProcessed = 1)

View file

@ -175,7 +175,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend
}
"get the correct types of dispatchers" in {
//All created/obtained dispatchers are of the expected type/instance
// All created/obtained dispatchers are of the expected type/instance
assert(typesAndValidators.forall(tuple => tuple._2(allDispatchers(tuple._1))))
}

View file

@ -89,7 +89,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
{
val c = config.getConfig("akka.actor.default-dispatcher")
//General dispatcher config
// General dispatcher config
{
c.getString("type") should ===("Dispatcher")
@ -100,13 +100,13 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
c.getBoolean("attempt-teamwork") should ===(true)
}
//Default executor config
// Default executor config
{
val pool = c.getConfig("default-executor")
pool.getString("fallback") should ===("fork-join-executor")
}
//Fork join executor config
// Fork join executor config
{
val pool = c.getConfig("fork-join-executor")
@ -116,7 +116,7 @@ class ConfigSpec extends AkkaSpec(ConfigFactory.defaultReference(ActorSystem.fin
pool.getString("task-peeking-mode") should be("FIFO")
}
//Thread pool executor config
// Thread pool executor config
{
val pool = c.getConfig("thread-pool-executor")

View file

@ -27,16 +27,16 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
val es = Executors.newCachedThreadPool()
try {
val executor: Executor with ExecutionContext = ExecutionContext.fromExecutor(es)
executor should not be (null)
executor should not be null
val executorService: ExecutorService with ExecutionContext = ExecutionContext.fromExecutorService(es)
executorService should not be (null)
executorService should not be null
val jExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(es)
jExecutor should not be (null)
jExecutor should not be null
val jExecutorService: ExecutionContextExecutorService = ExecutionContexts.fromExecutorService(es)
jExecutorService should not be (null)
jExecutorService should not be null
} finally {
es.shutdown
}
@ -60,7 +60,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
(1 to 100).foreach { _ =>
batchable {
if (callingThreadLock.get != 0) p.tryFailure(new IllegalStateException("Batch was executed inline!"))
else if (count.incrementAndGet == 100) p.trySuccess(()) //Done
else if (count.incrementAndGet == 100) p.trySuccess(()) // Done
else if (lock.compareAndSet(0, 1)) {
try Thread.sleep(10)
finally lock.compareAndSet(1, 0)

View file

@ -82,7 +82,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
}
}
//CANDIDATE FOR TESTKIT
// CANDIDATE FOR TESTKIT
def spawn[T <: AnyRef](fun: => T): Future[T] = Future(fun)(ExecutionContext.global)
def createMessageInvocation(msg: Any): Envelope = Envelope(msg, system.deadLetters, system)
@ -138,7 +138,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
val q = factory(config)
ensureInitialMailboxState(config, q)
EventFilter.warning(pattern = "received dead letter", occurrences = (enqueueN - dequeueN)).intercept {
EventFilter.warning(pattern = "received dead letter", 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))
@ -171,13 +171,13 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
val ps = producers.map(Await.result(_, remainingOrDefault))
val cs = 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
//No message is allowed to be consumed by more than one consumer
ps.map(_.size).sum should ===(enqueueN) // Must have produced 1000 messages
cs.map(_.size).sum should ===(dequeueN) // Must have consumed all produced messages
// No message is allowed to be consumed by more than one consumer
cs.flatten.distinct.size should ===(dequeueN)
//All consumed messages should have been produced
// All consumed messages should have been produced
cs.flatten.diff(ps.flatten).size should ===(0)
//The ones that were produced and not consumed
// The ones that were produced and not consumed
ps.flatten.diff(cs.flatten).size should ===(enqueueN - dequeueN)
}
}

View file

@ -28,14 +28,14 @@ object PriorityDispatcherSpec {
class Unbounded(@unused settings: ActorSystem.Settings, @unused config: Config)
extends UnboundedPriorityMailbox(PriorityGenerator({
case i: Int => i //Reverse order
case i: Int => i // Reverse order
case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int))
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
extends BoundedPriorityMailbox(PriorityGenerator({
case i: Int => i //Reverse order
case i: Int => i // Reverse order
case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int), 1000, 10 seconds)

View file

@ -308,7 +308,7 @@ class ScanningEventBusSpec extends EventBusSpec("ScanningEventBus") {
def createNewEventBus(): BusType = new MyScanningEventBus
def createEvents(numberOfEvents: Int) = (0 until numberOfEvents)
def createEvents(numberOfEvents: Int) = 0 until numberOfEvents
def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }
@ -339,7 +339,7 @@ class LookupEventBusSpec extends EventBusSpec("LookupEventBus") {
def createNewEventBus(): BusType = new MyLookupEventBus
def createEvents(numberOfEvents: Int) = (0 until numberOfEvents)
def createEvents(numberOfEvents: Int) = 0 until numberOfEvents
def createSubscriber(pipeTo: ActorRef) = new Procedure[Int] { def apply(i: Int) = pipeTo ! i }

View file

@ -74,10 +74,10 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
"An EventStream" must {
"manage subscriptions" in {
//#event-bus-start-unsubscriber-scala
// #event-bus-start-unsubscriber-scala
val bus = new EventStream(system, true)
bus.startUnsubscriber()
//#event-bus-start-unsubscriber-scala
// #event-bus-start-unsubscriber-scala
bus.subscribe(testActor, classOf[M])
bus.publish(M(42))

View file

@ -96,7 +96,7 @@ object LoggerSpec {
sender() ! LoggerInitialized
case SetTarget(ref, `qualifier`) =>
target = Some(ref)
ref ! ("OK")
ref ! "OK"
case event: LogEvent if !event.mdc.isEmpty =>
print(event)
target.foreach { _ ! event }
@ -173,7 +173,7 @@ class LoggerSpec extends AnyWordSpec with Matchers {
"log messages to standard output" in {
val out = createSystemAndLogToBuffer("defaultLogger", defaultConfig, true)
out.size should be > (0)
out.size should be > 0
}
"drain logger queue on system.terminate" in {

View file

@ -68,7 +68,8 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll {
system.eventStream.subscribe(testActor, classOf[UnhandledMessage])
val a = system.actorOf(Props(new Actor {
def receive =
new LoggingReceive(Some("funky"), {
new LoggingReceive(Some("funky"),
{
case null =>
})
}))

View file

@ -58,9 +58,9 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
val record = expectMsgType[logging.LogRecord]
record should not be (null)
record.getMillis should not be (0)
record.getThreadID should not be (0)
record should not be null
record.getMillis should not be 0
record.getThreadID should not be 0
record.getLevel should ===(logging.Level.SEVERE)
record.getMessage should ===("Simulated error")
record.getThrown.getClass should ===(classOf[JavaLoggerSpec.SimulatedExc])
@ -73,9 +73,9 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
val record = expectMsgType[logging.LogRecord]
record should not be (null)
record.getMillis should not be (0)
record.getThreadID should not be (0)
record should not be null
record.getMillis should not be 0
record.getThreadID should not be 0
record.getLevel should ===(logging.Level.INFO)
record.getMessage should ===("3 is the magic number")
record.getThrown should ===(null)

View file

@ -405,7 +405,8 @@ class TcpConnectionSpec extends AkkaSpec("""
connectionActor ! ResumeReading
connectionHandler.expectMsgType[Received].data.decodeString("ASCII") should ===(vs)
} finally shutdown(system)
}
finally shutdown(system)
}
"close the connection and reply with `Closed` upon reception of a `Close` command" in
@ -653,7 +654,7 @@ class TcpConnectionSpec extends AkkaSpec("""
override lazy val connectionActor =
createConnectionActor(serverAddress = UnboundAddress, timeout = Option(100.millis))
run {
connectionActor.toString should not be ("")
connectionActor.toString should not be ""
userHandler.expectMsg(CommandFailed(Connect(UnboundAddress, timeout = Option(100.millis))))
watch(connectionActor)
expectTerminated(connectionActor)
@ -982,7 +983,7 @@ class TcpConnectionSpec extends AkkaSpec("""
override def run(body: => Unit): Unit = super.run {
try {
serverSideChannel.configureBlocking(false)
serverSideChannel should not be (null)
serverSideChannel should not be null
interestCallReceiver.expectMsg(OP_CONNECT)
selector.send(connectionActor, ChannelConnectable)

View file

@ -50,7 +50,7 @@ trait TcpIntegrationSpecSupport { this: AkkaSpec =>
connectCommander.sender() ! Register(clientHandler.ref)
bindHandler.expectMsgType[Connected] match {
case Connected(`localAddress`, `endpoint`) => //ok
case Connected(`localAddress`, `endpoint`) => // ok
case other => fail(s"No match: ${other}")
}
val serverHandler = TestProbe()

View file

@ -227,7 +227,8 @@ class AsyncDnsResolverSpec extends AkkaSpec("""
def resolver(clients: List[ActorRef], config: Config): ActorRef = {
val settings = new DnsSettings(system.asInstanceOf[ExtendedActorSystem], config)
system.actorOf(Props(new AsyncDnsResolver(settings, new SimpleDnsCache(), (_, _) => {
system.actorOf(Props(new AsyncDnsResolver(settings, new SimpleDnsCache(),
(_, _) => {
clients
})))
}

View file

@ -253,7 +253,7 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender with Eventually
}
EventFilter.warning(pattern = ".*boom.*", occurrences = 1).intercept {
supervisor ! "boom" //this will be sent to deadLetters
supervisor ! "boom" // this will be sent to deadLetters
expectNoMessage(500.milliseconds)
}
}

View file

@ -349,7 +349,7 @@ class CircuitBreakerSpec extends AkkaSpec("""
breaker().currentFailureCount should ===(0)
intercept[TestException] {
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" }
}
breaker().currentFailureCount should ===(1)
breaker().withSyncCircuitBreaker(sayHi)
@ -362,7 +362,7 @@ class CircuitBreakerSpec extends AkkaSpec("""
breaker().currentFailureCount should ===(0)
intercept[TestException] {
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" }
}
breaker().currentFailureCount should ===(1)
@ -385,7 +385,7 @@ class CircuitBreakerSpec extends AkkaSpec("""
breaker().currentFailureCount should ===(0)
intercept[TestException] {
val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread
breaker().withSyncCircuitBreaker({ if (Thread.currentThread() eq ct) throwException else "fail" })
breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" }
}
breaker().currentFailureCount should ===(1)
breaker().succeed()

View file

@ -29,10 +29,10 @@ class RetrySpec extends AkkaSpec with RetrySupport {
@volatile var counter = 0
val retried = retry(
() =>
Future.successful({
Future.successful {
counter += 1
counter
}),
},
5,
1 second)
@ -94,7 +94,8 @@ class RetrySpec extends AkkaSpec with RetrySupport {
} else Future.successful(5)
}
val retried = retry(() => attempt(), 5, attempted => {
val retried = retry(() => attempt(), 5,
attempted => {
attemptedCount = attempted
Some(100.milliseconds * attempted)
})

View file

@ -232,12 +232,12 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
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 msgs2 = router.sendToAll(await = false) // make sure the routees are still busy after the first batch of messages get processed.
val before = System.nanoTime()
resizer.reportMessageCount(router.routees, router.msgs.size) //updates the records
resizer.reportMessageCount(router.routees, router.msgs.size) // updates the records
msgs1.foreach(_.second.open()) //process two messages
msgs1.foreach(_.second.open()) // process two messages
// make sure some time passes in-between
Thread.sleep(300)
@ -263,12 +263,12 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
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 msgs2 = router.sendToAll(await = false) // make sure the routees are still busy after the first batch of messages get processed.
val before = System.nanoTime()
resizer.reportMessageCount(router.routees, router.msgs.size) //updates the records
resizer.reportMessageCount(router.routees, router.msgs.size) // updates the records
msgs1.foreach(_.second.open()) //process two messages
msgs1.foreach(_.second.open()) // process two messages
// make sure some time passes in-between
Thread.sleep(300)

View file

@ -77,7 +77,7 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
actor ! akka.routing.Broadcast("end")
Await.ready(doneLatch, 5 seconds)
replies.values.foreach { _ should be > (0) }
replies.values.foreach { _ should be > 0 }
replies.values.sum should ===(iterationCount * connectionCount)
}

View file

@ -227,7 +227,7 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
val z = routeeSize(router)
z should be > (2)
z should be > 2
Thread.sleep((300 millis).dilated.toMillis)

View file

@ -136,15 +136,15 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"set supplied supervisorStrategy" in {
//#supervision
// #supervision
val escalator = OneForOneStrategy() {
//#custom-strategy
// #custom-strategy
case e => testActor ! e; SupervisorStrategy.Escalate
//#custom-strategy
// #custom-strategy
}
val router =
system.actorOf(RoundRobinPool(1, supervisorStrategy = escalator).props(routeeProps = Props[TestActor]()))
//#supervision
// #supervision
router ! GetRoutees
EventFilter[ActorKilledException](occurrences = 1).intercept {
expectMsgType[Routees].routees.head.send(Kill, testActor)

View file

@ -29,8 +29,8 @@ object ScatterGatherFirstCompletedSpec {
Props(new Actor {
def receive = {
case Stop(None) => context.stop(self)
case Stop(Some(_id)) if (_id == id) => context.stop(self)
case _id: Int if (_id == id) =>
case Stop(Some(_id)) if _id == id => context.stop(self)
case _id: Int if _id == id =>
case _ => {
Thread.sleep(100 * id)
sender() ! id

View file

@ -51,15 +51,15 @@ class SmallestMailboxSpec extends AkkaSpec with DefaultTimeout with ImplicitSend
busy.countDown()
val busyPath = usedActors.get(0)
busyPath should not be (null)
busyPath should not be null
val path1 = usedActors.get(1)
val path2 = usedActors.get(2)
val path3 = usedActors.get(3)
path1 should not be (busyPath)
path2 should not be (busyPath)
path3 should not be (busyPath)
path1 should not be busyPath
path2 should not be busyPath
path3 should not be busyPath
}
}

View file

@ -183,7 +183,7 @@ class BoundedBlockingQueueSpec
// queue.take() must happen first
Thread.sleep(50) // this is why this test is tagged as TimingTest
events should contain(awaitNotEmpty)
events should not contain (poll)
events should not contain poll
}
"block until the backing queue is non-empty" taggedAs TimingTest in {
@ -557,7 +557,7 @@ class BoundedBlockingQueueSpec
val target = mutable.Buffer[String]()
elems.foreach(queue.put)
queue.drainTo(target.asJava)
elems should contain theSameElementsAs (target)
elems should contain theSameElementsAs target
}
}
@ -617,7 +617,7 @@ class BoundedBlockingQueueSpec
queue.retainAll(elems.asJava) should equal(true)
queue.remainingCapacity() should equal(1)
queue.toArray() shouldNot contain("Akka")
queue.toArray() should contain theSameElementsAs (elems)
queue.toArray() should contain theSameElementsAs elems
}
"return false if no elements were removed" in {

View file

@ -313,10 +313,10 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
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
.collect { // Since there is no partial put on LongBuffer, we need to collect only the interesting bytes
case (r, i) if byteOrder == ByteOrder.LITTLE_ENDIAN && i % elemSize < nBytes => r
case (r, i) if byteOrder == ByteOrder.BIG_ENDIAN && i % elemSize >= (elemSize - nBytes) => r
})
}
.toSeq == builder.result()
}
@ -886,13 +886,13 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
"calling span" in {
check { (a: ByteString, b: Byte) =>
likeVector(a)({ _.span(_ != b) match { case (a, b) => (a, b) } })
likeVector(a) { _.span(_ != b) match { case (a, b) => (a, b) } }
}
}
"calling takeWhile" in {
check { (a: ByteString, b: Byte) =>
likeVector(a)({ _.takeWhile(_ != b) })
likeVector(a) { _.takeWhile(_ != b) }
}
}
"calling dropWhile" in {
@ -940,9 +940,9 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
check { (slice: ByteStringSlice) =>
slice match {
case (xs, from, until) =>
likeVector(xs)({
likeVector(xs) {
_.slice(from, until)
})
}
}
}
}
@ -951,9 +951,9 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
check { (slice: ByteStringSlice) =>
slice match {
case (xs, from, until) =>
likeVector(xs)({
likeVector(xs) {
_.drop(from).take(until - from)
})
}
}
}
}
@ -970,11 +970,11 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers {
check { (slice: ByteStringSlice) =>
slice match {
case (xs, from, until) =>
likeVector(xs)({ it =>
likeVector(xs) { it =>
val array = new Array[Byte](xs.length)
it.copyToArray(array, from, until)
array.toSeq
})
}
}
}
}

View file

@ -44,52 +44,52 @@ class FrequencyListSpec extends AnyWordSpec with Matchers {
check(frequency, Nil)
frequency.update("a")
check(frequency, List( /* 1: */ "a"))
check(frequency, List(/* 1: */ "a"))
frequency.update("b").update("c")
check(frequency, List( /* 1: */ "a", "b", "c"))
check(frequency, List(/* 1: */ "a", "b", "c"))
frequency.update("a").update("c")
check(frequency, List( /* 1: */ "b", /* 2: */ "a", "c"))
check(frequency, List(/* 1: */ "b", /* 2: */ "a", "c"))
frequency.update("d").update("e").update("f").update("g")
check(frequency, List( /* 1: */ "b", "d", "e", "f", "g", /* 2: */ "a", "c"))
check(frequency, List(/* 1: */ "b", "d", "e", "f", "g", /* 2: */ "a", "c"))
frequency.update("c").update("f")
check(frequency, List( /* 1: */ "b", "d", "e", "g", /* 2: */ "a", "f", /* 3: */ "c"))
check(frequency, List(/* 1: */ "b", "d", "e", "g", /* 2: */ "a", "f", /* 3: */ "c"))
frequency.remove("d").remove("g").remove("b").remove("f")
check(frequency, List( /* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
check(frequency, List(/* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
frequency.update("e").update("h").update("i")
check(frequency, List( /* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
check(frequency, List(/* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
frequency.removeLeastFrequent(3) shouldBe List("h", "i", "a")
check(frequency, List( /* 2: */ "e", /* 3: */ "c"))
check(frequency, List(/* 2: */ "e", /* 3: */ "c"))
frequency.update("j").update("k").update("l").update("m")
check(frequency, List( /* 1: */ "j", "k", "l", "m", /* 2: */ "e", /* 3: */ "c"))
check(frequency, List(/* 1: */ "j", "k", "l", "m", /* 2: */ "e", /* 3: */ "c"))
frequency.removeLeastFrequent(skip = OptionVal.Some("j")) shouldBe List("k")
check(frequency, List( /* 1: */ "j", "l", "m", /* 2: */ "e", /* 3: */ "c"))
check(frequency, List(/* 1: */ "j", "l", "m", /* 2: */ "e", /* 3: */ "c"))
frequency.removeLeastFrequent(2, skip = OptionVal.Some("l")) shouldBe List("j", "m")
check(frequency, List( /* 1: */ "l", /* 2: */ "e", /* 3: */ "c"))
check(frequency, List(/* 1: */ "l", /* 2: */ "e", /* 3: */ "c"))
frequency.update("n").update("o").update("p").update("e").update("o").update("l")
check(frequency, List( /* 1: */ "n", "p", /* 2: */ "o", "l", /* 3: */ "c", "e"))
check(frequency, List(/* 1: */ "n", "p", /* 2: */ "o", "l", /* 3: */ "c", "e"))
frequency.removeMostFrequent(3) shouldBe List("e", "c", "l")
check(frequency, List( /* 1: */ "n", "p", /* 2: */ "o"))
check(frequency, List(/* 1: */ "n", "p", /* 2: */ "o"))
frequency.update("q").update("r").update("p").update("o").update("n")
check(frequency, List( /* 1: */ "q", "r", /* 2: */ "p", "n", /* 3: */ "o"))
check(frequency, List(/* 1: */ "q", "r", /* 2: */ "p", "n", /* 3: */ "o"))
frequency.removeMostFrequent(skip = OptionVal.Some("o")) shouldBe List("n")
check(frequency, List( /* 1: */ "q", "r", /* 2: */ "p", /* 3: */ "o"))
check(frequency, List(/* 1: */ "q", "r", /* 2: */ "p", /* 3: */ "o"))
frequency.removeMostFrequent(2, skip = OptionVal.Some("p")) shouldBe List("o", "r")
check(frequency, List( /* 1: */ "q", /* 2: */ "p"))
check(frequency, List(/* 1: */ "q", /* 2: */ "p"))
}
"track overall recency of elements when enabled" in {
@ -100,72 +100,72 @@ class FrequencyListSpec extends AnyWordSpec with Matchers {
clock.tick() // time = 1
frequency.update("a")
check(frequency, List( /* 1: */ "a"))
check(frequency, List(/* 1: */ "a"))
checkRecency(frequency, List("a"))
clock.tick() // time = 2
frequency.update("b").update("c")
check(frequency, List( /* 1: */ "a", "b", "c"))
check(frequency, List(/* 1: */ "a", "b", "c"))
checkRecency(frequency, List("a", "b", "c"))
clock.tick() // time = 3
frequency.update("a").update("c")
check(frequency, List( /* 1: */ "b", /* 2: */ "a", "c"))
check(frequency, List(/* 1: */ "b", /* 2: */ "a", "c"))
checkRecency(frequency, List("b", "a", "c"))
clock.tick() // time = 4
frequency.update("d").update("e").update("f")
check(frequency, List( /* 1: */ "b", "d", "e", "f", /* 2: */ "a", "c"))
check(frequency, List(/* 1: */ "b", "d", "e", "f", /* 2: */ "a", "c"))
checkRecency(frequency, List("b", "a", "c", "d", "e", "f"))
clock.tick() // time = 5
frequency.update("c").update("f")
check(frequency, List( /* 1: */ "b", "d", "e", /* 2: */ "a", "f", /* 3: */ "c"))
check(frequency, List(/* 1: */ "b", "d", "e", /* 2: */ "a", "f", /* 3: */ "c"))
checkRecency(frequency, List("b", "a", "d", "e", "c", "f"))
clock.tick() // time = 6
frequency.remove("d").remove("b").remove("f")
check(frequency, List( /* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
check(frequency, List(/* 1: */ "e", /* 2: */ "a", /* 3: */ "c"))
checkRecency(frequency, List("a", "e", "c"))
clock.tick() // time = 7
frequency.update("e").update("h").update("i")
check(frequency, List( /* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
check(frequency, List(/* 1: */ "h", "i", /* 2: */ "a", "e", /* 3: */ "c"))
checkRecency(frequency, List("a", "c", "e", "h", "i"))
clock.tick() // time = 8
frequency.removeOverallLeastRecent() shouldBe List("a")
check(frequency, List( /* 1: */ "h", "i", /* 2: */ "e", /* 3: */ "c"))
check(frequency, List(/* 1: */ "h", "i", /* 2: */ "e", /* 3: */ "c"))
checkRecency(frequency, List("c", "e", "h", "i"))
clock.tick() // time = 9
frequency.update("i").update("j").update("k")
check(frequency, List( /* 1: */ "h", "j", "k", /* 2: */ "e", "i", /* 3: */ "c"))
check(frequency, List(/* 1: */ "h", "j", "k", /* 2: */ "e", "i", /* 3: */ "c"))
checkRecency(frequency, List("c", "e", "h", "i", "j", "k"))
clock.tick() // time = 10
frequency.removeOverallMostRecent() shouldBe List("k")
check(frequency, List( /* 1: */ "h", "j", /* 2: */ "e", "i", /* 3: */ "c"))
check(frequency, List(/* 1: */ "h", "j", /* 2: */ "e", "i", /* 3: */ "c"))
checkRecency(frequency, List("c", "e", "h", "i", "j"))
clock.tick() // time = 11
frequency.removeOverallLeastRecentOutside(3.seconds) shouldBe List("c", "e", "h")
check(frequency, List( /* 1: */ "j", /* 2: */ "i"))
check(frequency, List(/* 1: */ "j", /* 2: */ "i"))
checkRecency(frequency, List("i", "j"))
clock.tick() // time = 12
frequency.update("l").update("m")
check(frequency, List( /* 1: */ "j", "l", "m", /* 2: */ "i"))
check(frequency, List(/* 1: */ "j", "l", "m", /* 2: */ "i"))
checkRecency(frequency, List("i", "j", "l", "m"))
clock.tick() // time = 13
frequency.removeOverallMostRecentWithin(3.seconds) shouldBe List("m", "l")
check(frequency, List( /* 1: */ "j", /* 2: */ "i"))
check(frequency, List(/* 1: */ "j", /* 2: */ "i"))
checkRecency(frequency, List("i", "j"))
clock.tick() // time = 14
frequency.update("n").update("o").update("n")
check(frequency, List( /* 1: */ "j", "o", /* 2: */ "i", "n"))
check(frequency, List(/* 1: */ "j", "o", /* 2: */ "i", "n"))
checkRecency(frequency, List("i", "j", "o", "n"))
}
@ -177,80 +177,80 @@ class FrequencyListSpec extends AnyWordSpec with Matchers {
check(aging, Nil)
for (_ <- 1 to 10) regular.update("a").update("b").update("c")
check(regular, List( /*10*/ "a", "b", "c"))
check(regular, List(/*10*/ "a", "b", "c"))
for (_ <- 1 to 10) aging.update("a").update("b").update("c")
check(aging, List( /*10+0*/ "a", "b", "c"))
check(aging, List(/*10+0*/ "a", "b", "c"))
// age = 0
regular.update("x").update("y").update("z")
check(regular, List( /*1*/ "x", "y", "z", /*10*/ "a", "b", "c"))
check(regular, List(/*1*/ "x", "y", "z", /*10*/ "a", "b", "c"))
aging.update("x").update("y").update("z")
check(aging, List( /*1+0*/ "x", "y", "z", /*10+0*/ "a", "b", "c"))
check(aging, List(/*1+0*/ "x", "y", "z", /*10+0*/ "a", "b", "c"))
regular.removeLeastFrequent() shouldBe List("x")
check(regular, List( /*1*/ "y", "z", /*10*/ "a", "b", "c"))
check(regular, List(/*1*/ "y", "z", /*10*/ "a", "b", "c"))
aging.removeLeastFrequent() shouldBe List("x")
check(aging, List( /*1+0*/ "y", "z", /*10+0*/ "a", "b", "c"))
check(aging, List(/*1+0*/ "y", "z", /*10+0*/ "a", "b", "c"))
// age = 1 (from last removal of "x")
regular.update("x").update("y").update("z").update("z")
check(regular, List( /*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
check(regular, List(/*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
aging.update("x").update("y").update("z").update("z")
check(aging, List( /*1+1*/ "x", /*2+1*/ "y", /*3+1*/ "z", /*10+0*/ "a", "b", "c"))
check(aging, List(/*1+1*/ "x", /*2+1*/ "y", /*3+1*/ "z", /*10+0*/ "a", "b", "c"))
regular.removeLeastFrequent(2) shouldBe List("x", "y")
check(regular, List( /*3*/ "z", /*10*/ "a", "b", "c"))
check(regular, List(/*3*/ "z", /*10*/ "a", "b", "c"))
aging.removeLeastFrequent(2) shouldBe List("x", "y")
check(aging, List( /*3+1*/ "z", /*10+0*/ "a", "b", "c"))
check(aging, List(/*3+1*/ "z", /*10+0*/ "a", "b", "c"))
// age = 3 (from last removal of "y")
regular.update("x").update("y").update("z")
check(regular, List( /*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
check(regular, List(/*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
aging.update("x").update("y").update("z")
check(aging, List( /*1+3*/ "x", "y", /*4+3*/ "z", /*10+0*/ "a", "b", "c"))
check(aging, List(/*1+3*/ "x", "y", /*4+3*/ "z", /*10+0*/ "a", "b", "c"))
regular.removeLeastFrequent(3) shouldBe List("x", "y", "z")
check(regular, List( /*10*/ "a", "b", "c"))
check(regular, List(/*10*/ "a", "b", "c"))
aging.removeLeastFrequent(3) shouldBe List("x", "y", "z")
check(aging, List( /*10+0*/ "a", "b", "c"))
check(aging, List(/*10+0*/ "a", "b", "c"))
// age = 7 (from last removal of "z")
regular.update("x").update("y").update("y").update("z").update("z").update("z")
check(regular, List( /*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
check(regular, List(/*1*/ "x", /*2*/ "y", /*3*/ "z", /*10*/ "a", "b", "c"))
aging.update("x").update("y").update("y").update("z").update("z").update("z")
check(aging, List( /*1+7*/ "x", /*2+7*/ "y", /*10+0*/ "a", "b", "c", /*3+7*/ "z"))
check(aging, List(/*1+7*/ "x", /*2+7*/ "y", /*10+0*/ "a", "b", "c", /*3+7*/ "z"))
regular.removeLeastFrequent(2) shouldBe List("x", "y")
check(regular, List( /*3*/ "z", /*10*/ "a", "b", "c"))
check(regular, List(/*3*/ "z", /*10*/ "a", "b", "c"))
aging.removeLeastFrequent(2) shouldBe List("x", "y")
check(aging, List( /*10+0*/ "a", "b", "c", /*3+7*/ "z"))
check(aging, List(/*10+0*/ "a", "b", "c", /*3+7*/ "z"))
// age = 9 (from last removal of "y")
regular.update("x").update("y").update("z")
check(regular, List( /*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
check(regular, List(/*1*/ "x", "y", /*4*/ "z", /*10*/ "a", "b", "c"))
aging.update("x").update("y").update("z")
check(aging, List( /*10+0*/ "a", "b", "c", /*1+9*/ "x", "y", /*4+9*/ "z"))
check(aging, List(/*10+0*/ "a", "b", "c", /*1+9*/ "x", "y", /*4+9*/ "z"))
regular.removeLeastFrequent(3) shouldBe List("x", "y", "z")
check(regular, List( /*10*/ "a", "b", "c"))
check(regular, List(/*10*/ "a", "b", "c"))
aging.removeLeastFrequent(3) shouldBe List("a", "b", "c")
check(aging, List( /*1+9*/ "x", "y", /*4+9*/ "z"))
check(aging, List(/*1+9*/ "x", "y", /*4+9*/ "z"))
// age = 10 (from last removal of "c")
}

View file

@ -19,7 +19,8 @@ import akka.testkit.DefaultTimeout
class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
implicit val ec: ExecutionContextExecutor = system.dispatcher
private def emptyIndex =
new Index[String, Int](100, new Comparator[Int] {
new Index[String, Int](100,
new Comparator[Int] {
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
})
@ -58,11 +59,11 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
index.put("s1", 2)
index.put("s2", 1)
index.put("s2", 2)
//Remove value
// Remove value
index.remove("s1", 1) should ===(true)
index.remove("s1", 1) should ===(false)
index.valueIterator("s1").toSet should ===(Set(2))
//Remove key
// Remove key
index.remove("s2") match {
case Some(iter) => iter.toSet should ===(Set(1, 2))
case None => fail()
@ -101,16 +102,17 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout {
index.isEmpty should ===(true)
}
"be able to be accessed in parallel" in {
val index = new Index[Int, Int](100, new Comparator[Int] {
val index = new Index[Int, Int](100,
new Comparator[Int] {
override def compare(a: Int, b: Int): Int = Integer.compare(a, b)
})
val nrOfTasks = 10000
val nrOfKeys = 10
val nrOfValues = 10
//Fill index
// Fill index
for (key <- 0 until nrOfKeys; value <- 0 until nrOfValues)
index.put(key, value)
//Tasks to be executed in parallel
// Tasks to be executed in parallel
def putTask() = Future {
index.put(Random.nextInt(nrOfKeys), Random.nextInt(nrOfValues))
}

View file

@ -594,7 +594,9 @@ class ImmutableJavaBehaviorSpec extends Messages with Become with Stoppable {
class TransformMessagesJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse with Siphon {
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
val inbox = TestInbox[Command]("transformMessagesListener")
JBehaviors.transformMessages(classOf[Command], super.behavior(monitor)._1, pf(_.`match`(classOf[Command], fi(x => {
JBehaviors.transformMessages(classOf[Command], super.behavior(monitor)._1,
pf(_.`match`(classOf[Command],
fi(x => {
inbox.ref ! x
x
})))) -> inbox

View file

@ -120,7 +120,8 @@ class DeferredSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with L
// monitor is implemented with tap, so this is testing both
val probe = TestProbe[Event]("evt")
val monitorProbe = TestProbe[Command]("monitor")
val behv = Behaviors.monitor(monitorProbe.ref, Behaviors.setup[Command] { _ =>
val behv = Behaviors.monitor(monitorProbe.ref,
Behaviors.setup[Command] { _ =>
probe.ref ! Started
target(probe.ref)
})

View file

@ -483,7 +483,8 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
"be possible to combine with MDC" in {
val probe = createTestProbe[String]()
val ref = spawn(Behaviors.setup[Command] { _ =>
Behaviors.withMdc(staticMdc = Map("x" -> "y"), mdcForMessage = (msg: Command) => {
Behaviors.withMdc(staticMdc = Map("x" -> "y"),
mdcForMessage = (msg: Command) => {
probe.ref ! s"mdc:${msg.s.toUpperCase()}"
Map("msg" -> msg.s.toUpperCase())
}) {

View file

@ -103,7 +103,8 @@ class TestConsumer(
case job @ SomeAsyncJob(_, confirmTo, producerId, seqNr) =>
// when replacing producer the seqNr may start from 1 again
val cleanProcessed =
if (seqNr == 1L) processed.filterNot { case (pid, _) => pid == producerId } else processed
if (seqNr == 1L) processed.filterNot { case (pid, _) => pid == producerId }
else processed
if (cleanProcessed((producerId, seqNr)))
throw new RuntimeException(s"Received duplicate [($producerId,$seqNr)]")

View file

@ -62,7 +62,8 @@ class ActorSystemSpec
"An ActorSystem" must {
"start the guardian actor and terminate when it terminates" in {
withSystem("a", Behaviors.receiveMessage[Probe] { p =>
withSystem("a",
Behaviors.receiveMessage[Probe] { p =>
p.replyTo ! p.message
Behaviors.stopped
}, doTerminate = false) { sys =>

View file

@ -72,7 +72,8 @@ class AdaptationFailureSpec extends ScalaTestWithActorTestKit with AnyWordSpecLi
val probe = createTestProbe[Any]()
val threw = Promise[Done]()
val ref = spawn(Behaviors.setup[Any] { ctx =>
val adapter = ctx.messageAdapter[Any](classOf[Any], { _ =>
val adapter = ctx.messageAdapter[Any](classOf[Any],
{ _ =>
threw.success(Done)
throw TestException("boom")
})

View file

@ -119,13 +119,13 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
}
"contain the class name where the first log was called" in {
val eventFilter = LoggingTestKit.custom({
val eventFilter = LoggingTestKit.custom {
case event if event.loggerName == classOf[ActorLoggingSpec].getName =>
true
case event =>
println(event.loggerName)
false
})
}
eventFilter.expect(spawn(Behaviors.setup[String] { context =>
context.log.info("Started")
@ -139,23 +139,23 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
}
"contain the object class name where the first log was called" in {
val eventFilter = LoggingTestKit.custom({
val eventFilter = LoggingTestKit.custom {
case event if event.loggerName == WhereTheBehaviorIsDefined.getClass.getName => true
case other =>
println(other.loggerName)
false
})
}
eventFilter.expect(spawn(WhereTheBehaviorIsDefined.behavior, "the-actor-with-object"))
}
"contain the abstract behavior class name where the first log was called" in {
val eventFilter = LoggingTestKit.custom({
val eventFilter = LoggingTestKit.custom {
case event if event.loggerName == classOf[BehaviorWhereTheLoggerIsUsed].getName => true
case other =>
println(other.loggerName)
false
})
}
eventFilter.expect {
spawn(Behaviors.setup[String](context => new BehaviorWhereTheLoggerIsUsed(context)), "the-actor-with-behavior")
@ -200,7 +200,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
true // any is fine, we're just after the right count of statements reaching the listener
}
.withOccurrences(36)
.expect({
.expect {
spawn(Behaviors.setup[String] {
context =>
context.log.debug("message")
@ -247,7 +247,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
Behaviors.stopped
})
})
}
}
"use Slf4jLogger from akka-slf4j automatically" in {
@ -490,8 +490,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
Map(
ActorMdc.AkkaAddressKey -> system.classicSystem.asInstanceOf[ExtendedActorSystem].provider.addressString,
ActorMdc.AkkaSourceKey -> actorPath.get.toString,
ActorMdc.SourceActorSystemKey -> system.name)
)
ActorMdc.SourceActorSystemKey -> system.name))
true
} catch {
case ex: Throwable =>

View file

@ -231,7 +231,7 @@ class AdapterSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll with
}
"allow seamless access to untyped extensions" in {
SerializationExtension(typedSystem) should not be (null)
SerializationExtension(typedSystem) should not be null
}
}

View file

@ -14,7 +14,7 @@ import org.scalatest.wordspec.AnyWordSpecLike
object AggregatorSpec {
object IllustrateUsage {
//#usage
// #usage
object Hotel1 {
final case class RequestQuote(replyTo: ActorRef[Quote])
final case class Quote(hotel: String, price: BigDecimal)
@ -65,7 +65,7 @@ object AggregatorSpec {
}
}
}
//#usage
// #usage
}
}

View file

@ -42,7 +42,7 @@ object DispatchersDocSpec {
val yourBehavior: Behavior[String] = Behaviors.same
val example = Behaviors.receive[Any] { (context, _) =>
//#spawn-dispatcher
// #spawn-dispatcher
import akka.actor.typed.DispatcherSelector
context.spawn(yourBehavior, "DefaultDispatcher")
@ -50,7 +50,7 @@ object DispatchersDocSpec {
context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking())
context.spawn(yourBehavior, "ParentDispatcher", DispatcherSelector.sameAsParent())
context.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"))
//#spawn-dispatcher
// #spawn-dispatcher
Behaviors.same
}

View file

@ -16,10 +16,10 @@ import org.scalatest.wordspec.AnyWordSpecLike
object FSMDocSpec {
//#simple-state
//#simple-events
// #simple-state
// #simple-events
object Buncher {
//#simple-state
// #simple-state
// FSM event becomes the type of the message Actor supports
sealed trait Event
@ -27,17 +27,17 @@ object FSMDocSpec {
final case class Queue(obj: Any) extends Event
case object Flush extends Event
private case object Timeout extends Event
//#simple-events
// #simple-events
//#storing-state
// #storing-state
sealed trait Data
case object Uninitialized extends Data
final case class Todo(target: ActorRef[Batch], queue: immutable.Seq[Any]) extends Data
final case class Batch(obj: immutable.Seq[Any])
//#storing-state
// #storing-state
//#simple-state
// #simple-state
// states of the FSM represented as behaviors
// initial state
@ -67,10 +67,10 @@ object FSMDocSpec {
}
}
//#simple-events
// #simple-events
}
//#simple-events
//#simple-state
// #simple-events
// #simple-state
}
class FSMDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCapturing {

View file

@ -22,7 +22,7 @@ import akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit
object GracefulStopDocSpec {
//#master-actor
// #master-actor
object MasterControlProgram {
sealed trait Command
@ -51,9 +51,9 @@ object GracefulStopDocSpec {
}
}
}
//#master-actor
// #master-actor
//#worker-actor
// #worker-actor
object Job {
sealed trait Command
@ -66,10 +66,10 @@ object GracefulStopDocSpec {
}
}
}
//#worker-actor
// #worker-actor
object IllustrateWatch {
//#master-actor-watch
// #master-actor-watch
object MasterControlProgram {
sealed trait Command
@ -93,11 +93,11 @@ object GracefulStopDocSpec {
}
}
}
//#master-actor-watch
// #master-actor-watch
}
object IllustrateWatchWith {
//#master-actor-watchWith
// #master-actor-watchWith
object MasterControlProgram {
sealed trait Command
@ -121,7 +121,7 @@ object GracefulStopDocSpec {
}
}
}
//#master-actor-watchWith
// #master-actor-watchWith
}
}
@ -133,7 +133,7 @@ class GracefulStopDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike
"Graceful stop example" must {
"start some workers" in {
//#start-workers
// #start-workers
import MasterControlProgram._
val system: ActorSystem[Command] = ActorSystem(MasterControlProgram(), "B6700")
@ -148,7 +148,7 @@ class GracefulStopDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike
system.terminate()
Await.result(system.whenTerminated, 3.seconds)
//#start-workers
// #start-workers
}
"gracefully stop workers and master" in {

View file

@ -170,7 +170,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
"contain a sample for scheduling messages to self" in {
//#timer
// #timer
object Buncher {
sealed trait Command
@ -214,7 +214,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
}
}
}
//#timer
// #timer
val probe = createTestProbe[Buncher.Batch]()
val buncher: ActorRef[Buncher.Command] = spawn(Buncher(probe.ref, 1.second, 10))
@ -581,7 +581,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
}
"contain a sample for pipeToSelf" in {
//#pipeToSelf
// #pipeToSelf
trait CustomerDataAccess {
def update(value: Customer): Future[Done]
@ -632,7 +632,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec
}
}
}
//#pipeToSelf
// #pipeToSelf
val dataAccess = new CustomerDataAccess {
override def update(value: Customer): Future[Done] = Future.successful(Done)

View file

@ -109,7 +109,7 @@ object IntroSpec {
final case class SayHello(name: String)
//#hello-world-main-with-dispatchers
// #hello-world-main-with-dispatchers
def apply(): Behavior[SayHello] =
Behaviors.setup { context =>
val dispatcherPath = "akka.actor.default-blocking-io-dispatcher"
@ -124,21 +124,21 @@ object IntroSpec {
Behaviors.same
}
}
//#hello-world-main-with-dispatchers
// #hello-world-main-with-dispatchers
}
}
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
object ChatRoom {
//#chatroom-behavior
// #chatroom-behavior
sealed trait RoomCommand
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends RoomCommand
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
private final case class PublishSessionMessage(screenName: String, message: String) extends RoomCommand
//#chatroom-behavior
//#chatroom-protocol
// #chatroom-behavior
// #chatroom-protocol
sealed trait SessionEvent
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
@ -148,8 +148,8 @@ object IntroSpec {
sealed trait SessionCommand
final case class PostMessage(message: String) extends SessionCommand
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
def apply(): Behavior[RoomCommand] =
chatRoom(List.empty)
@ -185,24 +185,24 @@ object IntroSpec {
client ! message
Behaviors.same
}
//#chatroom-protocol
// #chatroom-protocol
}
//#chatroom-behavior
//#chatroom-protocol
// #chatroom-behavior
// #chatroom-protocol
//#chatroom-gabbler
// #chatroom-gabbler
object Gabbler {
import ChatRoom._
def apply(): Behavior[SessionEvent] =
Behaviors.setup { context =>
Behaviors.receiveMessage {
//#chatroom-gabbler
// #chatroom-gabbler
// We document that the compiler warns about the missing handler for `SessionDenied`
case SessionDenied(reason) =>
context.log.info("cannot start chat room session: {}", reason)
Behaviors.stopped
//#chatroom-gabbler
// #chatroom-gabbler
case SessionGranted(handle) =>
handle ! PostMessage("Hello World!")
Behaviors.same
@ -212,9 +212,9 @@ object IntroSpec {
}
}
}
//#chatroom-gabbler
// #chatroom-gabbler
//#chatroom-main
// #chatroom-main
object Main {
def apply(): Behavior[NotUsed] =
Behaviors.setup { context =>
@ -234,7 +234,7 @@ object IntroSpec {
}
}
//#chatroom-main
// #chatroom-main
}
@ -244,7 +244,7 @@ class IntroSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogC
"Intro sample" must {
"say hello" in {
//#hello-world
// #hello-world
val system: ActorSystem[HelloWorldMain.SayHello] =
ActorSystem(HelloWorldMain(), "hello")
@ -252,7 +252,7 @@ class IntroSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogC
system ! HelloWorldMain.SayHello("World")
system ! HelloWorldMain.SayHello("Akka")
//#hello-world
// #hello-world
Thread.sleep(500) // it will not fail if too short
ActorTestKit.shutdown(system)

View file

@ -26,14 +26,14 @@ object LoggingDocExamples {
def howToUse(): Unit = {
//#context-log
// #context-log
Behaviors.receive[String] { (context, message) =>
context.log.info("Received message: {}", message)
Behaviors.same
}
//#context-log
// #context-log
//#logger-name
// #logger-name
Behaviors.setup[String] { context =>
context.setLoggerName("com.myservice.BackendManager")
context.log.info("Starting up")
@ -43,9 +43,9 @@ object LoggingDocExamples {
Behaviors.same
}
}
//#logger-name
// #logger-name
//#logger-factory
// #logger-factory
val log = LoggerFactory.getLogger("com.myservice.BackendTask")
Future {
@ -55,21 +55,21 @@ object LoggingDocExamples {
case Success(result) => log.info("Task completed: {}", result)
case Failure(exc) => log.error("Task failed", exc)
}
//#logger-factory
// #logger-factory
}
def placeholders(): Unit = {
//#info2
// #info2
import akka.actor.typed.scaladsl.LoggerOps
Behaviors.receive[String] { (context, message) =>
context.log.info2("{} received message: {}", context.self.path.name, message)
Behaviors.same
}
//#info2
// #info2
//#infoN
// #infoN
import akka.actor.typed.scaladsl.LoggerOps
Behaviors.receive[String] { (context, message) =>
@ -80,23 +80,23 @@ object LoggingDocExamples {
message.take(10))
Behaviors.same
}
//#infoN
// #infoN
}
def logMessages(): Unit = {
//#logMessages
// #logMessages
import akka.actor.typed.LogOptions
import org.slf4j.event.Level
Behaviors.logMessages(LogOptions().withLevel(Level.TRACE), BackendManager())
//#logMessages
// #logMessages
}
def withMdc(): Unit = {
val system: ActorSystem[_] = ???
//#withMdc
// #withMdc
val staticMdc = Map("startTime" -> system.startTime.toString)
Behaviors.withMdc[BackendManager.Command](
staticMdc,
@ -104,7 +104,7 @@ object LoggingDocExamples {
(msg: BackendManager.Command) => Map("identifier" -> msg.identifier, "upTime" -> system.uptime.toString)) {
BackendManager()
}
//#withMdc
// #withMdc
}
def logging(): Unit = {
@ -112,18 +112,18 @@ object LoggingDocExamples {
final case class Message(s: String)
val ref: ActorRef[Message] = ???
//#test-logging
// #test-logging
import akka.actor.testkit.typed.scaladsl.LoggingTestKit
// implicit ActorSystem is needed, but that is given by ScalaTestWithActorTestKit
//implicit val system: ActorSystem[_]
// implicit val system: ActorSystem[_]
LoggingTestKit.info("Received message").expect {
ref ! Message("hello")
}
//#test-logging
// #test-logging
//#test-logging-criteria
// #test-logging-criteria
LoggingTestKit
.error[IllegalArgumentException]
.withMessageRegex(".*was rejected.*expecting ascii input.*")
@ -138,15 +138,15 @@ object LoggingDocExamples {
ref ! Message("hellö")
ref ! Message("hejdå")
}
//#test-logging-criteria
// #test-logging-criteria
}
def tagsExample(): Unit = {
Behaviors.setup[AnyRef] { context =>
val myBehavior = Behaviors.empty[AnyRef]
//#tags
// #tags
context.spawn(myBehavior, "MyActor", ActorTags("processing"))
//#tags
// #tags
Behaviors.stopped
}
}

View file

@ -22,17 +22,17 @@ import org.scalatest.wordspec.AnyWordSpecLike
object OOIntroSpec {
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
object ChatRoom {
//#chatroom-behavior
// #chatroom-behavior
sealed trait RoomCommand
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends RoomCommand
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
private final case class PublishSessionMessage(screenName: String, message: String) extends RoomCommand
//#chatroom-behavior
//#chatroom-protocol
// #chatroom-behavior
// #chatroom-protocol
sealed trait SessionEvent
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
@ -42,8 +42,8 @@ object OOIntroSpec {
sealed trait SessionCommand
final case class PostMessage(message: String) extends SessionCommand
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
def apply(): Behavior[RoomCommand] =
Behaviors.setup(context => new ChatRoomBehavior(context))
@ -96,12 +96,12 @@ object OOIntroSpec {
Behaviors.same
}
}
//#chatroom-protocol
// #chatroom-protocol
}
//#chatroom-protocol
//#chatroom-behavior
// #chatroom-protocol
// #chatroom-behavior
//#chatroom-gabbler
// #chatroom-gabbler
object Gabbler {
import ChatRoom._
@ -119,10 +119,10 @@ object OOIntroSpec {
Behaviors.stopped
}
}
//#chatroom-gabbler
// #chatroom-gabbler
}
//#chatroom-main
// #chatroom-main
object Main {
def apply(): Behavior[NotUsed] =
Behaviors.setup { context =>
@ -142,7 +142,7 @@ object OOIntroSpec {
}
}
//#chatroom-main
// #chatroom-main
}

View file

@ -33,7 +33,7 @@ object RouterSpec {
// #routee
//intentionally out of the routee section
// intentionally out of the routee section
class DoBroadcastLog(text: String) extends Worker.DoLog(text)
object DoBroadcastLog {
def apply(text: String) = new DoBroadcastLog(text)
@ -93,17 +93,17 @@ class RouterSpec extends ScalaTestWithActorTestKit("akka.loglevel=warning") with
val alternativeRouter = ctx.spawn(alternativePool, "alternative-pool")
alternativeRouter ! Worker.DoLog("msg")
//#pool
// #pool
// #broadcast
val poolWithBroadcast = pool.withBroadcastPredicate(_.isInstanceOf[DoBroadcastLog])
val routerWithBroadcast = ctx.spawn(poolWithBroadcast, "pool-with-broadcast")
//this will be sent to all 4 routees
// this will be sent to all 4 routees
routerWithBroadcast ! DoBroadcastLog("msg")
Behaviors.empty
// #broadcast
}
//#pool
// #pool
)
probe.receiveMessages(15)
@ -164,17 +164,17 @@ class RouterSpec extends ScalaTestWithActorTestKit("akka.loglevel=warning") with
}
}
//registering proxies
// registering proxies
val proxy1 = spawn(Proxy(probe1.ref))
val proxy2 = spawn(Proxy(probe2.ref))
val waiterProbe = createTestProbe[Receptionist.Registered]()
system.receptionist ! Receptionist.Register(Proxy.RegisteringKey, proxy1, waiterProbe.ref)
system.receptionist ! Receptionist.Register(Proxy.RegisteringKey, proxy2, waiterProbe.ref)
//wait until both registrations get Receptionist.Registered
// wait until both registrations get Receptionist.Registered
waiterProbe.receiveMessages(2)
//messages sent to a router with consistent hashing
// messages sent to a router with consistent hashing
// #consistent-hashing
val router = spawn(Routers.group(Proxy.RegisteringKey).withConsistentHashingRouting(10, Proxy.mapping))
@ -185,8 +185,8 @@ class RouterSpec extends ScalaTestWithActorTestKit("akka.loglevel=warning") with
router ! Proxy.Message("zh3", "Text4")
// the hash is calculated over the Proxy.Message first parameter obtained through the Proxy.mapping function
// #consistent-hashing
//Then messages with equal Message.id reach the same actor
//so the first message in each probe queue is equal to its second
// Then messages with equal Message.id reach the same actor
// so the first message in each probe queue is equal to its second
probe1.receiveMessage() shouldBe probe1.receiveMessage()
probe2.receiveMessage() shouldBe probe2.receiveMessage()

View file

@ -34,7 +34,7 @@ object SpawnProtocolDocSpec {
// Silent because we want to name the unused 'context' parameter
@nowarn("msg=never used")
//#main
// #main
object HelloWorldMain {
def apply(): Behavior[SpawnProtocol.Command] =
Behaviors.setup { context =>
@ -44,7 +44,7 @@ object SpawnProtocolDocSpec {
SpawnProtocol()
}
}
//#main
// #main
}
class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCapturing {
@ -53,7 +53,7 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLik
"ActorSystem with SpawnProtocol" must {
"be able to spawn actors" in {
//#system-spawn
// #system-spawn
implicit val system: ActorSystem[SpawnProtocol.Command] =
ActorSystem(HelloWorldMain(), "hello")
@ -78,7 +78,7 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLik
greeterRef ! HelloWorld.Greet("Akka", replyToRef)
}
//#system-spawn
// #system-spawn
Thread.sleep(500) // it will not fail if too short
ActorTestKit.shutdown(system)

View file

@ -31,15 +31,15 @@ object StyleGuideDocExamples {
object FunctionalStyle {
//#fun-style
// #fun-style
//#messages
// #messages
object Counter {
sealed trait Command
case object Increment extends Command
final case class GetValue(replyTo: ActorRef[Value]) extends Command
final case class Value(n: Int)
//#messages
// #messages
def apply(): Behavior[Command] =
counter(0)
@ -56,16 +56,16 @@ object StyleGuideDocExamples {
Behaviors.same
}
}
//#messages
// #messages
}
//#messages
//#fun-style
// #messages
// #fun-style
}
object OOStyle {
//#oo-style
// #oo-style
object Counter {
sealed trait Command
@ -95,7 +95,7 @@ object StyleGuideDocExamples {
}
}
}
//#oo-style
// #oo-style
}
@ -270,7 +270,7 @@ object StyleGuideDocExamples {
}
object FactoryMethod {
//#behavior-factory-method
// #behavior-factory-method
object CountDown {
sealed trait Command
case object Down extends Command
@ -284,7 +284,7 @@ object StyleGuideDocExamples {
import CountDown._
private def counter(remaining: Int): Behavior[Command] = {
//#exhastivness-check
// #exhastivness-check
Behaviors.receiveMessage {
case Down =>
if (remaining == 1) {
@ -293,28 +293,28 @@ object StyleGuideDocExamples {
} else
counter(remaining - 1)
}
//#exhastivness-check
// #exhastivness-check
}
}
//#behavior-factory-method
// #behavior-factory-method
object Usage {
val context: ActorContext[_] = ???
val doneRef: ActorRef[Done] = ???
//#behavior-factory-method-spawn
// #behavior-factory-method-spawn
val countDown = context.spawn(CountDown(100, doneRef), "countDown")
//#behavior-factory-method-spawn
// #behavior-factory-method-spawn
//#message-prefix-in-tell
// #message-prefix-in-tell
countDown ! CountDown.Down
//#message-prefix-in-tell
// #message-prefix-in-tell
}
}
object Messages {
//#message-protocol
// #message-protocol
object CounterProtocol {
sealed trait Command
@ -325,11 +325,11 @@ object StyleGuideDocExamples {
case object Confirmed extends OperationResult
final case class Rejected(reason: String) extends OperationResult
}
//#message-protocol
// #message-protocol
}
object PublicVsPrivateMessages1 {
//#public-private-messages-1
// #public-private-messages-1
object Counter {
sealed trait Command
case object Increment extends Command
@ -366,11 +366,11 @@ object StyleGuideDocExamples {
Behaviors.same
}
}
//#public-private-messages-1
// #public-private-messages-1
}
object PublicVsPrivateMessages2 {
//#public-private-messages-2
// #public-private-messages-2
// above example is preferred, but this is possible and not wrong
object Counter {
// The type of all public and private messages the Counter actor handles
@ -417,7 +417,7 @@ object StyleGuideDocExamples {
Behaviors.same
}
}
//#public-private-messages-2
// #public-private-messages-2
}
object Ask {
@ -425,7 +425,7 @@ object StyleGuideDocExamples {
implicit val system: ActorSystem[Nothing] = ???
//#ask-1
// #ask-1
import akka.actor.typed.scaladsl.AskPattern._
import akka.util.Timeout
@ -433,11 +433,11 @@ object StyleGuideDocExamples {
val counter: ActorRef[Command] = ???
val result: Future[OperationResult] = counter.ask(replyTo => Increment(delta = 2, replyTo))
//#ask-1
// #ask-1
//#ask-2
// #ask-2
val result2: Future[OperationResult] = counter.ask(Increment(delta = 2, _))
//#ask-2
// #ask-2
/*
//#ask-3
@ -446,26 +446,26 @@ object StyleGuideDocExamples {
//#ask-3
*/
//#ask-4
// #ask-4
val result3: Future[OperationResult] = counter ? (Increment(delta = 2, _))
//#ask-4
// #ask-4
}
object ExhaustivenessCheck {
object CountDown {
//#messages-sealed
// #messages-sealed
sealed trait Command
case object Down extends Command
final case class GetValue(replyTo: ActorRef[Value]) extends Command
final case class Value(n: Int)
//#messages-sealed
// #messages-sealed
}
class CountDown() {
import CountDown._
//#pattern-match-unhandled
// #pattern-match-unhandled
val zero: Behavior[Command] = {
Behaviors.receiveMessage {
case GetValue(replyTo) =>
@ -475,11 +475,11 @@ object StyleGuideDocExamples {
Behaviors.unhandled
}
}
//#pattern-match-unhandled
// #pattern-match-unhandled
@nowarn
object partial {
//#pattern-match-partial
// #pattern-match-partial
val zero: Behavior[Command] = {
Behaviors.receiveMessagePartial {
case GetValue(replyTo) =>
@ -487,7 +487,7 @@ object StyleGuideDocExamples {
Behaviors.same
}
}
//#pattern-match-partial
// #pattern-match-partial
}
}
@ -495,22 +495,22 @@ object StyleGuideDocExamples {
object BehaviorCompositionWithPartialFunction {
//#messages-sealed-composition
// #messages-sealed-composition
sealed trait Command
case object Down extends Command
final case class GetValue(replyTo: ActorRef[Value]) extends Command
final case class Value(n: Int)
//#messages-sealed-composition
// #messages-sealed-composition
//#get-handler-partial
// #get-handler-partial
def getHandler(value: Int): PartialFunction[Command, Behavior[Command]] = {
case GetValue(replyTo) =>
replyTo ! Value(value)
Behaviors.same
}
//#get-handler-partial
// #get-handler-partial
//#set-handler-non-zero-partial
// #set-handler-non-zero-partial
def setHandlerNotZero(value: Int): PartialFunction[Command, Behavior[Command]] = {
case Down =>
if (value == 1)
@ -518,17 +518,17 @@ object StyleGuideDocExamples {
else
nonZero(value - 1)
}
//#set-handler-non-zero-partial
// #set-handler-non-zero-partial
//#set-handler-zero-partial
// #set-handler-zero-partial
def setHandlerZero(log: Logger): PartialFunction[Command, Behavior[Command]] = {
case Down =>
log.error("Counter is already at zero!")
Behaviors.same
}
//#set-handler-zero-partial
// #set-handler-zero-partial
//#top-level-behaviors-partial
// #top-level-behaviors-partial
val zero: Behavior[Command] = Behaviors.setup { context =>
Behaviors.receiveMessagePartial(getHandler(0).orElse(setHandlerZero(context.log)))
}
@ -538,13 +538,13 @@ object StyleGuideDocExamples {
// Default Initial Behavior for this actor
def apply(initialCapacity: Int): Behavior[Command] = nonZero(initialCapacity)
//#top-level-behaviors-partial
// #top-level-behaviors-partial
}
object NestingSample1 {
sealed trait Command
//#nesting
// #nesting
def apply(): Behavior[Command] =
Behaviors.setup[Command](context =>
Behaviors.withStash(100)(stash =>
@ -552,19 +552,19 @@ object StyleGuideDocExamples {
context.log.debug("Starting up")
// behavior using context, stash and timers ...
//#nesting
// #nesting
timers.isTimerActive("aa")
stash.isEmpty
Behaviors.empty
//#nesting
// #nesting
}))
//#nesting
// #nesting
}
object NestingSample2 {
sealed trait Command
//#nesting-supervise
// #nesting-supervise
def apply(): Behavior[Command] =
Behaviors.setup { context =>
// only run on initial actor start, not on crash-restart
@ -575,13 +575,13 @@ object StyleGuideDocExamples {
// every time the actor crashes and restarts a new stash is created (previous stash is lost)
context.log.debug("Starting up with stash")
// Behaviors.receiveMessage { ... }
//#nesting-supervise
// #nesting-supervise
stash.isEmpty
Behaviors.empty
//#nesting-supervise
// #nesting-supervise
})
.onFailure[RuntimeException](SupervisorStrategy.restart)
}
//#nesting-supervise
// #nesting-supervise
}
}

View file

@ -26,7 +26,7 @@ object ClassicWatchingTypedSpec {
def props() = classic.Props(new Classic)
}
//#classic-watch
// #classic-watch
class Classic extends classic.Actor with ActorLogging {
// context.spawn is an implicit extension method
val second: ActorRef[Typed.Command] =
@ -51,9 +51,9 @@ object ClassicWatchingTypedSpec {
context.stop(self)
}
}
//#classic-watch
// #classic-watch
//#typed
// #typed
object Typed {
sealed trait Command
final case class Ping(replyTo: ActorRef[Pong.type]) extends Command
@ -70,7 +70,7 @@ object ClassicWatchingTypedSpec {
}
}
}
//#typed
// #typed
}
class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
@ -80,9 +80,9 @@ class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
"Classic -> Typed" must {
"support creating, watching and messaging" in {
val system = classic.ActorSystem("Coexistence")
//#create-classic
// #create-classic
val classicActor = system.actorOf(Classic.props())
//#create-classic
// #create-classic
val probe = TestProbe()(system)
probe.watch(classicActor)
probe.expectTerminated(classicActor, 200.millis)
@ -90,11 +90,11 @@ class ClassicWatchingTypedSpec extends AnyWordSpec with LogCapturing {
}
"support converting a classic actor system to an actor system" in {
//#convert-classic
// #convert-classic
val system = akka.actor.ActorSystem("ClassicToTypedSystem")
val typedSystem: ActorSystem[Nothing] = system.toTyped
//#convert-classic
// #convert-classic
typedSystem.scheduler // remove compile warning
TestKit.shutdownActorSystem(system)
}

View file

@ -21,7 +21,7 @@ import scala.concurrent.duration._
object TypedWatchingClassicSpec {
//#typed
// #typed
object Typed {
final case class Ping(replyTo: akka.actor.typed.ActorRef[Pong.type])
sealed trait Command
@ -52,9 +52,9 @@ object TypedWatchingClassicSpec {
}
}
}
//#typed
// #typed
//#classic
// #classic
object Classic {
def props(): classic.Props = classic.Props(new Classic)
}
@ -64,7 +64,7 @@ object TypedWatchingClassicSpec {
replyTo ! Typed.Pong
}
}
//#classic
// #classic
}
class TypedWatchingClassicSpec extends AnyWordSpec with LogCapturing {
@ -73,10 +73,10 @@ class TypedWatchingClassicSpec extends AnyWordSpec with LogCapturing {
"Typed -> Classic" must {
"support creating, watching and messaging" in {
//#create
// #create
val system = classic.ActorSystem("TypedWatchingClassic")
val typed = system.spawn(Typed.behavior, "Typed")
//#create
// #create
val probe = TestProbe()(system)
probe.watch(typed.toClassic)
probe.expectTerminated(typed.toClassic, 200.millis)

View file

@ -51,10 +51,10 @@ object ExtensionDocSpec {
val initialBehavior: Behavior[Any] = Behaviors.empty[Any]
//#usage
// #usage
Behaviors.setup[Any] { ctx =>
DatabasePool(ctx.system).connection().executeQuery("insert into...")
initialBehavior
}
//#usage
// #usage
}

View file

@ -13,7 +13,7 @@ import akka.actor.Props
object ClassicSample {
//#hello-world-actor
// #hello-world-actor
object HelloWorld {
final case class Greet(whom: String)
final case class Greeted(whom: String)
@ -27,11 +27,11 @@ object ClassicSample {
override def receive: Receive = {
case Greet(whom) =>
//#fiddle_code
// #fiddle_code
log.info("Hello {}!", whom)
sender() ! Greeted(whom)
}
}
//#hello-world-actor
// #hello-world-actor
}

View file

@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors
object TypedSample {
//#hello-world-actor
// #hello-world-actor
object HelloWorld {
final case class Greet(whom: String, replyTo: ActorRef[Greeted])
final case class Greeted(whom: String, from: ActorRef[Greet])
@ -33,9 +33,9 @@ object TypedSample {
this
}
}
//#hello-world-actor
// #hello-world-actor
//#children
// #children
object Parent {
sealed trait Command
case class DelegateToChild(name: String, message: Child.Command) extends Command
@ -66,7 +66,7 @@ object TypedSample {
updated(Map.empty)
}
}
//#children
// #children
object Child {
sealed trait Command

View file

@ -17,37 +17,37 @@ object SupervisionCompileOnly {
val behavior = Behaviors.empty[String]
//#restart
// #restart
Behaviors.supervise(behavior).onFailure[IllegalStateException](SupervisorStrategy.restart)
//#restart
// #restart
//#resume
// #resume
Behaviors.supervise(behavior).onFailure[IllegalStateException](SupervisorStrategy.resume)
//#resume
// #resume
//#restart-limit
// #restart-limit
Behaviors
.supervise(behavior)
.onFailure[IllegalStateException](
SupervisorStrategy.restart.withLimit(maxNrOfRetries = 10, withinTimeRange = 10.seconds))
//#restart-limit
// #restart-limit
//#multiple
// #multiple
Behaviors
.supervise(Behaviors.supervise(behavior).onFailure[IllegalStateException](SupervisorStrategy.restart))
.onFailure[IllegalArgumentException](SupervisorStrategy.stop)
//#multiple
// #multiple
//#wrap
// #wrap
object Counter {
sealed trait Command
case class Increment(nr: Int) extends Command
case class GetCount(replyTo: ActorRef[Int]) extends Command
//#top-level
// #top-level
def apply(): Behavior[Command] =
Behaviors.supervise(counter(1)).onFailure(SupervisorStrategy.restart)
//#top-level
// #top-level
private def counter(count: Int): Behavior[Command] =
Behaviors.receiveMessage[Command] {
@ -58,9 +58,9 @@ object SupervisionCompileOnly {
Behaviors.same
}
}
//#wrap
// #wrap
//#restart-stop-children
// #restart-stop-children
def child(size: Long): Behavior[String] =
Behaviors.receiveMessage(msg => child(size + msg.length))
@ -82,9 +82,9 @@ object SupervisionCompileOnly {
}
.onFailure(SupervisorStrategy.restart)
}
//#restart-stop-children
// #restart-stop-children
//#restart-keep-children
// #restart-keep-children
def parent2: Behavior[String] = {
Behaviors.setup { ctx =>
val child1 = ctx.spawn(child(0), "child1")
@ -104,7 +104,7 @@ object SupervisionCompileOnly {
.onFailure(SupervisorStrategy.restart.withStopChildren(false))
}
}
//#restart-keep-children
// #restart-keep-children
trait Resource {
def close(): Unit
@ -113,7 +113,7 @@ object SupervisionCompileOnly {
def claimResource(): Resource = ???
@nowarn("msg=never used")
//#restart-PreRestart-signal
// #restart-PreRestart-signal
def withPreRestart: Behavior[String] = {
Behaviors
.supervise[String] {
@ -138,5 +138,5 @@ object SupervisionCompileOnly {
.onFailure[Exception](SupervisorStrategy.restart)
}
//#restart-PreRestart-signal
// #restart-PreRestart-signal
}

View file

@ -11,7 +11,7 @@ import scala.concurrent.{ ExecutionContextExecutor, Future }
import com.typesafe.config.{ Config, ConfigFactory }
import org.slf4j.Logger
import akka.{ Done, actor => classic }
import akka.{ actor => classic, Done }
import akka.actor.{ Address, BootstrapSetup, ClassicActorSystemProvider }
import akka.actor.setup.ActorSystemSetup
import akka.actor.typed.eventstream.EventStream

View file

@ -133,7 +133,6 @@ object Behavior {
* The `ClassTag` for `Outer` ensures that only messages of this class or a subclass thereof will be
* intercepted. Other message types (e.g. a private protocol) will bypass
* the interceptor and be continue to the inner behavior untouched.
*
*/
def transformMessages[Outer: ClassTag](matcher: PartialFunction[Outer, Inner]): Behavior[Outer] =
BehaviorImpl.transformMessages(behavior, matcher)

View file

@ -39,7 +39,6 @@ trait Scheduler {
* reach (calculated as: `delay / tickNanos > Int.MaxValue`).
*
* Note: For scheduling within actors `Behaviors.withTimers` or `ActorContext.scheduleOnce` should be preferred.
*
*/
def scheduleOnce(delay: java.time.Duration, runnable: Runnable, executor: ExecutionContext): Cancellable
@ -62,7 +61,6 @@ trait Scheduler {
* reach (calculated as: `delay / tickNanos > Int.MaxValue`).
*
* Note: For scheduling within actors `Behaviors.withTimers` should be preferred.
*
*/
def scheduleWithFixedDelay(initialDelay: FiniteDuration, delay: FiniteDuration)(runnable: Runnable)(
implicit executor: ExecutionContext): Cancellable
@ -124,7 +122,6 @@ trait Scheduler {
* reach (calculated as: `delay / tickNanos > Int.MaxValue`).
*
* Note: For scheduling within actors `Behaviors.withTimers` should be preferred.
*
*/
def scheduleAtFixedRate(initialDelay: FiniteDuration, interval: FiniteDuration)(runnable: Runnable)(
implicit executor: ExecutionContext): Cancellable

View file

@ -258,8 +258,7 @@ object ProducerControllerImpl {
settings: ProducerController.Settings,
initialState: Option[DurableProducerQueue.State[A]])(
thenBecomeActive: (
ActorRef[RequestNext[A]],
ActorRef[ConsumerController.Command[A]],
ActorRef[RequestNext[A]], ActorRef[ConsumerController.Command[A]],
DurableProducerQueue.State[A]) => Behavior[InternalCommand]): Behavior[InternalCommand] = {
Behaviors.receiveMessagePartial[InternalCommand] {
case RegisterConsumer(c: ActorRef[ConsumerController.Command[A]] @unchecked) =>
@ -346,7 +345,8 @@ object ProducerControllerImpl {
val manifest = Serializers.manifestFor(ser, mAnyRef)
val serializerId = ser.identifier
if (bytes.length <= chunkSize) {
ChunkedMessage(ByteString.fromArrayUnsafe(bytes), firstChunk = true, lastChunk = true, serializerId, manifest) :: Nil
ChunkedMessage(ByteString.fromArrayUnsafe(bytes), firstChunk = true, lastChunk = true, serializerId,
manifest) :: Nil
} else {
val builder = Vector.newBuilder[ChunkedMessage]
val chunksIter = ByteString.fromArrayUnsafe(bytes).grouped(chunkSize)

View file

@ -443,7 +443,8 @@ private class WorkPullingProducerControllerImpl[A: ClassTag](
currentSeqNr = s.currentSeqNr + 1,
preselectedWorkers =
s.preselectedWorkers.updated(s.currentSeqNr, PreselectedWorker(outKey, out.confirmationQualifier)),
handOver = s.handOver.updated(s.currentSeqNr, HandOver(resend.oldConfirmationQualifier, resend.oldSeqNr))))
handOver =
s.handOver.updated(s.currentSeqNr, HandOver(resend.oldConfirmationQualifier, resend.oldSeqNr))))
case None =>
checkStashFull(stashBuffer)
// no demand from any workers, or all already preselected

View file

@ -43,7 +43,6 @@ object EventStream {
* def subscribe(actorSystem: ActorSystem[_], actorRef: ActorRef[A]) =
* actorSystem.eventStream ! EventStream.Subscribe[A1](actorRef)
* }}}
*
*/
final case class Subscribe[E](subscriber: ActorRef[E])(implicit classTag: ClassTag[E]) extends Command {

View file

@ -218,7 +218,7 @@ import scala.util.Success
override def ask[Req, Res](target: RecipientRef[Req], createRequest: ActorRef[Res] => Req)(
mapResponse: Try[Res] => T)(implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit = {
import akka.actor.typed.scaladsl.AskPattern._
pipeToSelf((target.ask(createRequest))(responseTimeout, system.scheduler))(mapResponse)
pipeToSelf(target.ask(createRequest)(responseTimeout, system.scheduler))(mapResponse)
}
override def askWithStatus[Req, Res](target: RecipientRef[Req], createRequest: ActorRef[StatusReply[Res]] => Req)(

View file

@ -100,15 +100,15 @@ private[akka] trait ExtensionsImpl extends Extensions { self: ActorSystem[_] wit
}
} catch {
case t: Throwable =>
//In case shit hits the fan, remove the inProcess signal and escalate to caller
// In case shit hits the fan, remove the inProcess signal and escalate to caller
extensions.replace(ext, inProcessOfRegistration, t)
throw t
} finally {
//Always notify listeners of the inProcess signal
// Always notify listeners of the inProcess signal
inProcessOfRegistration.countDown()
}
case _ =>
//Someone else is in process of registering an extension for this Extension, retry
// Someone else is in process of registering an extension for this Extension, retry
registerExtension(ext)
}
}
@ -119,10 +119,10 @@ private[akka] trait ExtensionsImpl extends Extensions { self: ActorSystem[_] wit
@tailrec
private def findExtension[T <: Extension](ext: ExtensionId[T]): T = extensions.get(ext) match {
case c: CountDownLatch =>
//Registration in process, await completion and retry
// Registration in process, await completion and retry
c.await()
findExtension(ext)
case t: Throwable => throw t //Initialization failed, throw same again
case other => other.asInstanceOf[T] //could be a T or null, in which case we return the null as T
case t: Throwable => throw t // Initialization failed, throw same again
case other => other.asInstanceOf[T] // could be a T or null, in which case we return the null as T
}
}

View file

@ -95,7 +95,8 @@ private[akka] final class InterceptorImpl[O, I](
private def deduplicate(interceptedResult: Behavior[I], ctx: TypedActorContext[O]): Behavior[O] = {
val started = Behavior.start(interceptedResult, ctx.asInstanceOf[TypedActorContext[I]])
if (started == BehaviorImpl.UnhandledBehavior || started == BehaviorImpl.SameBehavior || !Behavior.isAlive(started)) {
if (started == BehaviorImpl.UnhandledBehavior || started == BehaviorImpl.SameBehavior || !Behavior.isAlive(
started)) {
started.unsafeCast[O]
} else {
// returned behavior could be nested in setups, so we need to start before we deduplicate

View file

@ -186,7 +186,8 @@ import java.util.function.Predicate
else {
val node = messages.next()
val message = wrap(node.message)
val interpretResult = try {
val interpretResult =
try {
message match {
case sig: Signal => Behavior.interpretSignal(b2, ctx, sig)
case msg => interpretUnstashedMessage(b2, ctx, msg, node)

View file

@ -303,7 +303,8 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
override protected def handleSignalException(
ctx: TypedActorContext[Any],
target: SignalTarget[T]): Catcher[Behavior[T]] = {
handleException(ctx, signalRestart = {
handleException(ctx,
signalRestart = {
case e: UnstashException[Any] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart)
case _ => target(ctx, PreRestart)
})
@ -311,7 +312,8 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
override protected def handleReceiveException(
ctx: TypedActorContext[Any],
target: ReceiveTarget[T]): Catcher[Behavior[T]] = {
handleException(ctx, signalRestart = {
handleException(ctx,
signalRestart = {
case e: UnstashException[Any] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart)
case _ => target.signalRestart(ctx)
})
@ -391,7 +393,8 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
case _ => newBehavior
}
nextBehavior.narrow
} catch handleException(ctx, signalRestart = {
} catch handleException(ctx,
signalRestart = {
case e: UnstashException[Any] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart)
case _ => ()
})

View file

@ -33,7 +33,6 @@ private[typed] object SystemMessageList {
}
/**
*
* INTERNAL API
*
* Value class supporting list operations on system messages. The `next` field of [[SystemMessage]]
@ -45,7 +44,6 @@ private[typed] object SystemMessageList {
*
* The type of the list also encodes that the messages contained are in reverse order, i.e. the head of the list is the
* latest appended element.
*
*/
private[typed] class LatestFirstSystemMessageList(val head: SystemMessage) extends AnyVal {
import SystemMessageList._
@ -94,7 +92,6 @@ private[typed] class LatestFirstSystemMessageList(val head: SystemMessage) exten
}
/**
*
* INTERNAL API
*
* Value class supporting list operations on system messages. The `next` field of [[SystemMessage]]
@ -106,7 +103,6 @@ private[typed] class LatestFirstSystemMessageList(val head: SystemMessage) exten
*
* This list type also encodes that the messages contained are in reverse order, i.e. the head of the list is the
* latest appended element.
*
*/
private[typed] class EarliestFirstSystemMessageList(val head: SystemMessage) extends AnyVal {
import SystemMessageList._

View file

@ -69,7 +69,7 @@ import scala.concurrent.duration.FiniteDuration
startTimerAtFixedRate(key, msg, initialDelay.asScala, interval.asScala)
override final def startPeriodicTimer(key: Any, msg: T, interval: Duration): Unit = {
//this follows the deprecation note in the super class
// this follows the deprecation note in the super class
startTimerWithFixedDelay(key, msg, interval.asScala)
}

View file

@ -118,7 +118,7 @@ import akka.util.OptionVal
if (c.hasTimer) {
msg match {
case timerMsg: TimerMsg =>
//we can only get this kind of message if the timer is of this concrete class
// we can only get this kind of message if the timer is of this concrete class
c.timer.asInstanceOf[TimerSchedulerImpl[T]].interceptTimerMsg(ctx.log, timerMsg) match {
case OptionVal.Some(m) =>
next(Behavior.interpretMessage(behavior, c, m), m)
@ -187,7 +187,8 @@ import akka.util.OptionVal
private def withSafelyAdapted[U, V](adapt: () => U)(body: U => V): Unit = {
var failed = false
val adapted: U = try {
val adapted: U =
try {
adapt()
} catch {
case NonFatal(ex) =>
@ -248,7 +249,8 @@ import akka.util.OptionVal
classic.SupervisorStrategy.Stop
else
ActorAdapter.classicSupervisorDecider(ex)
} finally {
}
finally {
ctx.clearCurrentActorThread()
}
}

View file

@ -197,7 +197,8 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider {
case None =>
}
updateServices(Set(key), { state =>
updateServices(Set(key),
{ state =>
val newState = state.serviceInstanceRemoved(key)(serviceInstance)
if (state.servicesPerActor.getOrElse(serviceInstance, Set.empty).isEmpty)
ctx.unwatch(serviceInstance)

View file

@ -27,7 +27,6 @@ import akka.util.JavaDurationConverters._
* message that is sent to the target Actor in order to function as a reply-to
* address, therefore the argument to the ask method is not the message itself
* but a function that given the reply-to address will create the message.
*
*/
object AskPattern {
@ -40,7 +39,7 @@ object AskPattern {
messageFactory: JFunction[ActorRef[Res], Req],
timeout: Duration,
scheduler: Scheduler): CompletionStage[Res] =
(actor.ask(messageFactory.apply)(timeout.asScala, scheduler)).toJava
actor.ask(messageFactory.apply)(timeout.asScala, scheduler).toJava
/**
* The same as [[ask]] but only for requests that result in a response of type [[akka.pattern.StatusReply]].
@ -53,6 +52,6 @@ object AskPattern {
messageFactory: JFunction[ActorRef[StatusReply[Res]], Req],
timeout: Duration,
scheduler: Scheduler): CompletionStage[Res] =
(actor.askWithStatus(messageFactory.apply)(timeout.asScala, scheduler).toJava)
actor.askWithStatus(messageFactory.apply)(timeout.asScala, scheduler).toJava
}

View file

@ -5,7 +5,7 @@
package akka.actor.typed.javadsl
import java.util.Collections
import java.util.function.{ Supplier, Function => JFunction }
import java.util.function.{ Function => JFunction, Supplier }
import scala.reflect.ClassTag
@ -154,7 +154,8 @@ object Behaviors {
def receive[T](
onMessage: JapiFunction2[ActorContext[T], T, Behavior[T]],
onSignal: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = {
new BehaviorImpl.ReceiveBehavior((ctx, msg) => onMessage.apply(ctx.asJava, msg), {
new BehaviorImpl.ReceiveBehavior((ctx, msg) => onMessage.apply(ctx.asJava, msg),
{
case (ctx, sig) => onSignal.apply(ctx.asJava, sig)
})
}
@ -327,7 +328,6 @@ object Behaviors {
* each message processing by the inner behavior is done.
* @param behavior The actual behavior handling the messages, the MDC is used for the log entries logged through
* `ActorContext.log`
*
*/
def withMdc[T](
interceptMessageClass: Class[T],
@ -344,7 +344,6 @@ object Behaviors {
* @param staticMdc This MDC is setup in the logging context for every message
* @param behavior The actual behavior handling the messages, the MDC is used for the log entries logged through
* `ActorContext.log`
*
*/
def withMdc[T](
interceptMessageClass: Class[T],
@ -369,7 +368,6 @@ object Behaviors {
* each message processing by the inner behavior is done.
* @param behavior The actual behavior handling the messages, the MDC is used for the log entries logged through
* `ActorContext.log`
*
*/
def withMdc[T](
interceptMessageClass: Class[T],

View file

@ -28,7 +28,6 @@ abstract class Receive[T] extends ExtensibleBehavior[T] {
* * returning `stopped` will terminate this Behavior
* * returning `same` designates to reuse the current Behavior
* * returning `unhandled` keeps the same Behavior and signals that the message was not yet handled
*
*/
@throws(classOf[Exception])
def receiveMessage(msg: T): Behavior[T]

View file

@ -77,9 +77,11 @@ final class ReceiveBuilder[T] private (
* @return this behavior builder
*/
def onMessageEquals(msg: T, handler: Creator[Behavior[T]]): ReceiveBuilder[T] =
withMessage(OptionVal.Some(msg.getClass), OptionVal.Some(new JPredicate[T] {
override def test(param: T): Boolean = param == (msg)
}), new JFunction[T, Behavior[T]] {
withMessage(OptionVal.Some(msg.getClass),
OptionVal.Some(new JPredicate[T] {
override def test(param: T): Boolean = param == msg
}),
new JFunction[T, Behavior[T]] {
// invoke creator without the message
override def apply(param: T): Behavior[T] = handler.create()
})
@ -128,9 +130,11 @@ final class ReceiveBuilder[T] private (
* @return this behavior builder
*/
def onSignalEquals(signal: Signal, handler: Creator[Behavior[T]]): ReceiveBuilder[T] =
withSignal(signal.getClass, OptionVal.Some(new JPredicate[Signal] {
withSignal(signal.getClass,
OptionVal.Some(new JPredicate[Signal] {
override def test(param: Signal): Boolean = param == signal
}), new JFunction[Signal, Behavior[T]] {
}),
new JFunction[Signal, Behavior[T]] {
override def apply(param: Signal): Behavior[T] = handler.create()
})

Some files were not shown because too many files have changed in this diff Show more