#3018 - Enabling -Xlint and dealing with the situation that occurs

This commit is contained in:
Viktor Klang 2013-03-28 23:45:48 +01:00
parent 88f7e28c6b
commit c883705242
75 changed files with 249 additions and 275 deletions

View file

@ -159,7 +159,7 @@ class ActorDSLSpec extends AkkaSpec {
become { become {
case "die" throw new Exception case "die" throw new Exception
} }
whenFailing { (cause, msg) testActor ! (cause, msg) } whenFailing { case m @ (cause, msg) testActor ! m }
whenRestarted { cause testActor ! cause } whenRestarted { cause testActor ! cause }
}) })
//#failing-actor //#failing-actor

View file

@ -43,19 +43,17 @@ object ActorRefSpec {
import context.system import context.system
def receive = { def receive = {
case "work" { case "work" {
work work()
sender ! "workDone" sender ! "workDone"
context.stop(self) context.stop(self)
} }
case ReplyTo(replyTo) { case ReplyTo(replyTo) {
work work()
replyTo ! "complexReply" replyTo ! "complexReply"
} }
} }
private def work { private def work(): Unit = Thread.sleep(1.second.dilated.toMillis)
Thread.sleep(1.second.dilated.toMillis)
}
} }
class SenderActor(replyActor: ActorRef, latch: TestLatch) extends Actor { class SenderActor(replyActor: ActorRef, latch: TestLatch) extends Actor {
@ -143,7 +141,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
new Actor { def receive = { case _ } } new Actor { def receive = { case _ } }
} }
def contextStackMustBeEmpty = ActorCell.contextStack.get.headOption must be === None def contextStackMustBeEmpty(): Unit = ActorCell.contextStack.get.headOption must be === None
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
intercept[akka.actor.ActorInitializationException] { intercept[akka.actor.ActorInitializationException] {
@ -154,7 +152,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
}))) })))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -163,7 +161,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result)))) actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -172,7 +170,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result))))))) actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -181,7 +179,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(promiseIntercept(new FailingInheritingOuterActor(actorOf(Props(new InnerActor))))(result)))) actorOf(Props(promiseIntercept(new FailingInheritingOuterActor(actorOf(Props(new InnerActor))))(result))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 2) intercept { EventFilter[ActorInitializationException](occurrences = 2) intercept {
@ -190,7 +188,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new FailingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) actorOf(Props(new FailingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 2) intercept { EventFilter[ActorInitializationException](occurrences = 2) intercept {
@ -199,7 +197,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new FailingInheritingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) actorOf(Props(new FailingInheritingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 2) intercept { EventFilter[ActorInitializationException](occurrences = 2) intercept {
@ -208,7 +206,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new FailingInheritingOuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result))))))) actorOf(Props(new FailingInheritingOuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -219,7 +217,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
})))))) }))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 2) intercept { EventFilter[ActorInitializationException](occurrences = 2) intercept {
@ -228,7 +226,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new FailingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) actorOf(Props(new FailingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -237,7 +235,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -246,7 +244,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({ new InnerActor; new InnerActor })(result))))))) actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({ new InnerActor; new InnerActor })(result)))))))
} }
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
EventFilter[ActorInitializationException](occurrences = 1) intercept { EventFilter[ActorInitializationException](occurrences = 1) intercept {
@ -255,7 +253,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout {
actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({ throw new IllegalStateException("Ur state be b0rked"); new InnerActor })(result))))))) actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({ throw new IllegalStateException("Ur state be b0rked"); new InnerActor })(result)))))))
}).getMessage must be === "Ur state be b0rked" }).getMessage must be === "Ur state be b0rked"
contextStackMustBeEmpty contextStackMustBeEmpty()
} }
} }

View file

@ -104,7 +104,7 @@ object Chameneos {
} }
} }
def run { def run(): Unit = {
// System.setProperty("akka.config", "akka.conf") // System.setProperty("akka.config", "akka.conf")
Chameneos.start = System.currentTimeMillis Chameneos.start = System.currentTimeMillis
val system = ActorSystem() val system = ActorSystem()
@ -114,5 +114,5 @@ object Chameneos {
system.shutdown() system.shutdown()
} }
def main(args: Array[String]): Unit = run def main(args: Array[String]): Unit = run()
} }

View file

@ -46,7 +46,7 @@ object FSMActorSpec {
case incomplete if incomplete.length < code.length case incomplete if incomplete.length < code.length
stay using CodeState(incomplete, code) stay using CodeState(incomplete, code)
case codeTry if (codeTry == code) { case codeTry if (codeTry == code) {
doUnlock doUnlock()
goto(Open) using CodeState("", code) forMax timeout goto(Open) using CodeState("", code) forMax timeout
} }
case wrong { case wrong {
@ -60,7 +60,7 @@ object FSMActorSpec {
when(Open) { when(Open) {
case Event(StateTimeout, _) { case Event(StateTimeout, _) {
doLock doLock()
goto(Locked) goto(Locked)
} }
} }
@ -87,19 +87,15 @@ object FSMActorSpec {
onTermination { onTermination {
case StopEvent(FSM.Shutdown, Locked, _) case StopEvent(FSM.Shutdown, Locked, _)
// stop is called from lockstate with shutdown as reason... // stop is called from lockstate with shutdown as reason...
terminatedLatch.open terminatedLatch.open()
} }
// initialize the lock // initialize the lock
initialize initialize
private def doLock() { private def doLock(): Unit = lockedLatch.open()
lockedLatch.open
}
private def doUnlock = { private def doUnlock(): Unit = unlockedLatch.open()
unlockedLatch.open
}
} }
case class CodeState(soFar: String, code: String) case class CodeState(soFar: String, code: String)

View file

@ -142,7 +142,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit
} }
"be canceled if cancel is performed before execution" in { "be canceled if cancel is performed before execution" in {
val task = collectCancellable(system.scheduler.scheduleOnce(10 seconds)()) val task = collectCancellable(system.scheduler.scheduleOnce(10 seconds)(()))
task.cancel() must be(true) task.cancel() must be(true)
task.isCancelled must be(true) task.isCancelled must be(true)
task.cancel() must be(false) task.cancel() must be(false)

View file

@ -68,8 +68,8 @@ object ActorModelSpec {
def interceptor = context.dispatcher.asInstanceOf[MessageDispatcherInterceptor] def interceptor = context.dispatcher.asInstanceOf[MessageDispatcherInterceptor]
def ack { def ack(): Unit = {
if (!busy.switchOn()) { if (!busy.switchOn(())) {
throw new Exception("isolation violated") throw new Exception("isolation violated")
} else { } else {
interceptor.getStats(self).msgsProcessed.incrementAndGet() interceptor.getStats(self).msgsProcessed.incrementAndGet()
@ -81,21 +81,21 @@ object ActorModelSpec {
} }
def receive = { def receive = {
case AwaitLatch(latch) { ack; latch.await(); busy.switchOff() } case AwaitLatch(latch) { ack(); latch.await(); busy.switchOff(()) }
case Meet(sign, wait) { ack; sign.countDown(); wait.await(); busy.switchOff() } case Meet(sign, wait) { ack(); sign.countDown(); wait.await(); busy.switchOff(()) }
case Wait(time) { ack; Thread.sleep(time); busy.switchOff() } case Wait(time) { ack(); Thread.sleep(time); busy.switchOff(()) }
case WaitAck(time, l) { ack; Thread.sleep(time); l.countDown(); busy.switchOff() } case WaitAck(time, l) { ack(); Thread.sleep(time); l.countDown(); busy.switchOff(()) }
case Reply(msg) { ack; sender ! msg; busy.switchOff() } case Reply(msg) { ack(); sender ! msg; busy.switchOff(()) }
case TryReply(msg) { ack; sender.tell(msg, null); busy.switchOff() } case TryReply(msg) { ack(); sender.tell(msg, null); busy.switchOff(()) }
case Forward(to, msg) { ack; to.forward(msg); busy.switchOff() } case Forward(to, msg) { ack(); to.forward(msg); busy.switchOff(()) }
case CountDown(latch) { ack; latch.countDown(); busy.switchOff() } case CountDown(latch) { ack(); latch.countDown(); busy.switchOff(()) }
case Increment(count) { ack; count.incrementAndGet(); busy.switchOff() } case Increment(count) { ack(); count.incrementAndGet(); busy.switchOff(()) }
case CountDownNStop(l) { ack; l.countDown(); context.stop(self); busy.switchOff() } case CountDownNStop(l) { ack(); l.countDown(); context.stop(self); busy.switchOff(()) }
case Restart { ack; busy.switchOff(); throw new Exception("Restart requested") } case Restart { ack(); busy.switchOff(()); throw new Exception("Restart requested") }
case Interrupt { ack; sender ! Status.Failure(new ActorInterruptedException(new InterruptedException("Ping!"))); busy.switchOff(); throw new InterruptedException("Ping!") } case Interrupt { ack(); sender ! Status.Failure(new ActorInterruptedException(new InterruptedException("Ping!"))); busy.switchOff(()); throw new InterruptedException("Ping!") }
case InterruptNicely(msg) { ack; sender ! msg; busy.switchOff(); Thread.currentThread().interrupt() } case InterruptNicely(msg) { ack(); sender ! msg; busy.switchOff(()); Thread.currentThread().interrupt() }
case ThrowException(e: Throwable) { ack; busy.switchOff(); throw e } case ThrowException(e: Throwable) { ack(); busy.switchOff(()); throw e }
case DoubleStop { ack; context.stop(self); context.stop(self); busy.switchOff } case DoubleStop { ack(); context.stop(self); context.stop(self); busy.switchOff }
} }
} }
@ -124,12 +124,12 @@ object ActorModelSpec {
} }
} }
abstract override def suspend(actor: ActorCell) { protected[akka] abstract override def suspend(actor: ActorCell) {
getStats(actor.self).suspensions.incrementAndGet() getStats(actor.self).suspensions.incrementAndGet()
super.suspend(actor) super.suspend(actor)
} }
abstract override def resume(actor: ActorCell) { protected[akka] abstract override def resume(actor: ActorCell) {
super.resume(actor) super.resume(actor)
getStats(actor.self).resumes.incrementAndGet() getStats(actor.self).resumes.incrementAndGet()
} }
@ -330,16 +330,12 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
} }
def spawn(f: Unit) { def spawn(f: Unit) {
val thread = new Thread { (new Thread {
override def run { override def run(): Unit =
try { try f catch {
f case e: Throwable system.eventStream.publish(Error(e, "spawn", this.getClass, "error in spawned thread"))
} catch {
case e system.eventStream.publish(Error(e, "spawn", this.getClass, "error in spawned thread"))
} }
} }).start()
}
thread.start()
} }
"not process messages for a suspended actor" in { "not process messages for a suspended actor" in {
@ -380,7 +376,7 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
try { try {
assertCountDown(cachedMessage.latch, waitTime, "Counting down from " + num) assertCountDown(cachedMessage.latch, waitTime, "Counting down from " + num)
} catch { } catch {
case e case e: Throwable
dispatcher match { dispatcher match {
case dispatcher: BalancingDispatcher case dispatcher: BalancingDispatcher
val team = dispatcher.team val team = dispatcher.team

View file

@ -55,7 +55,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout {
} }
callingThreadLock.compareAndSet(1, 0) // Disable the lock callingThreadLock.compareAndSet(1, 0) // Disable the lock
} }
Await.result(p.future, timeout.duration) must be === () Await.result(p.future, timeout.duration) must be === (())
} }
"be able to avoid starvation when Batching is used and Await/blocking is called" in { "be able to avoid starvation when Batching is used and Await/blocking is called" in {

View file

@ -573,11 +573,11 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
} }
"should not deadlock with nested await (ticket 1313)" in { "should not deadlock with nested await (ticket 1313)" in {
val simple = Future() map (_ Await.result((Future(()) map (_ ())), timeout.duration)) val simple = Future(()) map (_ Await.result((Future(()) map (_ ())), timeout.duration))
FutureSpec.ready(simple, timeout.duration) must be('completed) FutureSpec.ready(simple, timeout.duration) must be('completed)
val l1, l2 = new TestLatch val l1, l2 = new TestLatch
val complex = Future() map { _ val complex = Future(()) map { _
val nested = Future(()) val nested = Future(())
nested foreach (_ l1.open()) nested foreach (_ l1.open())
FutureSpec.ready(l1, TestLatch.DefaultTimeout) // make sure nested is completed FutureSpec.ready(l1, TestLatch.DefaultTimeout) // make sure nested is completed
@ -589,7 +589,7 @@ class FutureSpec extends AkkaSpec with Checkers with BeforeAndAfterAll with Defa
"re-use the same thread for nested futures with batching ExecutionContext" in { "re-use the same thread for nested futures with batching ExecutionContext" in {
val failCount = new java.util.concurrent.atomic.AtomicInteger val failCount = new java.util.concurrent.atomic.AtomicInteger
val f = Future() flatMap { _ val f = Future(()) flatMap { _
val originalThread = Thread.currentThread val originalThread = Thread.currentThread
// run some nested futures // run some nested futures
val nested = val nested =

View file

@ -637,7 +637,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms")
def interestsDesc(interests: Int): String = def interestsDesc(interests: Int): String =
interestsNames.filter(i (i._1 & interests) != 0).map(_._2).mkString(", ") interestsNames.filter(i (i._1 & interests) != 0).map(_._2).mkString(", ")
} }
def withUnacceptedConnection( private[io] def withUnacceptedConnection(
setServerSocketOptions: ServerSocketChannel Unit = _ (), setServerSocketOptions: ServerSocketChannel Unit = _ (),
connectionActorCons: (ActorRef, ActorRef) TestActorRef[TcpOutgoingConnection] = createConnectionActor())(body: UnacceptedSetup Any): Unit = connectionActorCons: (ActorRef, ActorRef) TestActorRef[TcpOutgoingConnection] = createConnectionActor())(body: UnacceptedSetup Any): Unit =

View file

@ -44,7 +44,7 @@ class PatternSpec extends AkkaSpec {
"complete Future with AskTimeoutException when actor not terminated within timeout" in { "complete Future with AskTimeoutException when actor not terminated within timeout" in {
val target = system.actorOf(Props[TargetActor]) val target = system.actorOf(Props[TargetActor])
val latch = TestLatch() val latch = TestLatch()
target ! (latch, remaining) target ! ((latch, remaining))
intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500 millis), remaining) } intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500 millis), remaining) }
latch.open() latch.open()
} }

View file

@ -11,7 +11,7 @@ class OrderbookTest extends JUnitSuite {
var tradeObserverMock: TradeObserver = null var tradeObserverMock: TradeObserver = null
@Before @Before
def setUp = { def setUp(): Unit = {
tradeObserverMock = mock(classOf[TradeObserver]) tradeObserverMock = mock(classOf[TradeObserver])
orderbook = new Orderbook("ERI") with TradeObserver { orderbook = new Orderbook("ERI") with TradeObserver {
def trade(bid: Bid, ask: Ask) = tradeObserverMock.trade(bid, ask) def trade(bid: Bid, ask: Ask) = tradeObserverMock.trade(bid, ask)
@ -19,7 +19,7 @@ class OrderbookTest extends JUnitSuite {
} }
@Test @Test
def shouldTradeSamePrice = { def shouldTradeSamePrice(): Unit = {
val bid = new Bid("ERI", 100, 1000) val bid = new Bid("ERI", 100, 1000)
val ask = new Ask("ERI", 100, 1000) val ask = new Ask("ERI", 100, 1000)
orderbook.addOrder(bid) orderbook.addOrder(bid)
@ -33,7 +33,7 @@ class OrderbookTest extends JUnitSuite {
} }
@Test @Test
def shouldTradeTwoLevels = { def shouldTradeTwoLevels(): Unit = {
val bid1 = new Bid("ERI", 101, 1000) val bid1 = new Bid("ERI", 101, 1000)
val bid2 = new Bid("ERI", 100, 1000) val bid2 = new Bid("ERI", 100, 1000)
val bid3 = new Bid("ERI", 99, 1000) val bid3 = new Bid("ERI", 99, 1000)
@ -62,7 +62,7 @@ class OrderbookTest extends JUnitSuite {
} }
@Test @Test
def shouldSplitBid = { def shouldSplitBid(): Unit = {
val bid = new Bid("ERI", 100, 300) val bid = new Bid("ERI", 100, 300)
val ask = new Ask("ERI", 100, 1000) val ask = new Ask("ERI", 100, 1000)
orderbook.addOrder(bid) orderbook.addOrder(bid)
@ -77,7 +77,7 @@ class OrderbookTest extends JUnitSuite {
} }
@Test @Test
def shouldSplitAsk = { def shouldSplitAsk(): Unit = {
val bid = new Bid("ERI", 100, 1000) val bid = new Bid("ERI", 100, 1000)
val ask = new Ask("ERI", 100, 600) val ask = new Ask("ERI", 100, 600)
orderbook.addOrder(bid) orderbook.addOrder(bid)

View file

@ -379,19 +379,19 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
val busy = TestLatch(1) val busy = TestLatch(1)
val received0 = TestLatch(1) val received0 = TestLatch(1)
router ! (busy, received0) router ! ((busy, received0))
Await.ready(received0, TestLatch.DefaultTimeout) Await.ready(received0, TestLatch.DefaultTimeout)
val received1 = TestLatch(1) val received1 = TestLatch(1)
router ! (1, received1) router ! ((1, received1))
Await.ready(received1, TestLatch.DefaultTimeout) Await.ready(received1, TestLatch.DefaultTimeout)
val received2 = TestLatch(1) val received2 = TestLatch(1)
router ! (2, received2) router ! ((2, received2))
Await.ready(received2, TestLatch.DefaultTimeout) Await.ready(received2, TestLatch.DefaultTimeout)
val received3 = TestLatch(1) val received3 = TestLatch(1)
router ! (3, received3) router ! ((3, received3))
Await.ready(received3, TestLatch.DefaultTimeout) Await.ready(received3, TestLatch.DefaultTimeout)
busy.countDown() busy.countDown()

View file

@ -329,8 +329,8 @@ class SerializationCompatibilitySpec extends AkkaSpec(SerializationTests.mostlyR
val ser = SerializationExtension(system) val ser = SerializationExtension(system)
"Cross-version serialization compatibility" must { "Cross-version serialization compatibility" must {
def verify(obj: Any, asExpected: String): Unit = def verify(obj: SystemMessage, asExpected: String): Unit =
String.valueOf(encodeHex(ser.serialize(obj, obj.getClass).get)) must be(asExpected) String.valueOf(ser.serialize((obj, obj.getClass)).map(encodeHex).get) must be === asExpected
"be preserved for the Create SystemMessage" in { "be preserved for the Create SystemMessage" in {
verify(Create(), "aced00057372000c7363616c612e5475706c6532bc7daadf46211a990200024c00025f317400124c6a6176612f6c616e672f4f626a6563743b4c00025f3271007e000178707372001b616b6b612e64697370617463682e7379736d73672e437265617465bcdf9f7f2675038d02000078707671007e0003") verify(Create(), "aced00057372000c7363616c612e5475706c6532bc7daadf46211a990200024c00025f317400124c6a6176612f6c616e672f4f626a6563743b4c00025f3271007e000178707372001b616b6b612e64697370617463682e7379736d73672e437265617465bcdf9f7f2675038d02000078707671007e0003")
@ -388,9 +388,9 @@ class OverriddenSystemMessageSerializationSpec extends AkkaSpec(SerializationTes
} }
} }
trait TestSerializable protected[akka] trait TestSerializable
class TestSerializer extends Serializer { protected[akka] class TestSerializer extends Serializer {
def includeManifest: Boolean = false def includeManifest: Boolean = false
def identifier = 9999 def identifier = 9999
@ -403,12 +403,12 @@ class TestSerializer extends Serializer {
} }
@SerialVersionUID(1) @SerialVersionUID(1)
case class FakeThrowable(msg: String) extends Throwable(msg) with Serializable { protected[akka] case class FakeThrowable(msg: String) extends Throwable(msg) with Serializable {
override def fillInStackTrace = null override def fillInStackTrace = null
} }
@SerialVersionUID(1) @SerialVersionUID(1)
case class FakeActorRef(name: String) extends InternalActorRef with ActorRefScope { protected[akka] case class FakeActorRef(name: String) extends InternalActorRef with ActorRefScope {
override def path = RootActorPath(Address("proto", "SomeSystem"), name) override def path = RootActorPath(Address("proto", "SomeSystem"), name)
override def forward(message: Any)(implicit context: ActorContext) = ??? override def forward(message: Any)(implicit context: ActorContext) = ???
override def isTerminated = ??? override def isTerminated = ???

View file

@ -89,7 +89,7 @@ class ByteStringSpec extends WordSpec with MustMatchers with Checkers {
val (bsAIt, bsBIt) = (a.iterator, b.iterator) val (bsAIt, bsBIt) = (a.iterator, b.iterator)
val (vecAIt, vecBIt) = (Vector(a: _*).iterator.buffered, Vector(b: _*).iterator.buffered) val (vecAIt, vecBIt) = (Vector(a: _*).iterator.buffered, Vector(b: _*).iterator.buffered)
(body(bsAIt, bsBIt) == body(vecAIt, vecBIt)) && (body(bsAIt, bsBIt) == body(vecAIt, vecBIt)) &&
(!strict || (bsAIt.toSeq, bsBIt.toSeq) == (vecAIt.toSeq, vecBIt.toSeq)) (!strict || (bsAIt.toSeq -> bsBIt.toSeq) == (vecAIt.toSeq -> vecBIt.toSeq))
} }
def likeVecBld(body: Builder[Byte, _] Unit): Boolean = { def likeVecBld(body: Builder[Byte, _] Unit): Boolean = {

View file

@ -17,17 +17,17 @@ class SwitchSpec extends WordSpec with MustMatchers {
s.isOff must be(true) s.isOff must be(true)
s.isOn must be(false) s.isOn must be(false)
s.switchOn("hello") must be(true) s.switchOn(()) must be(true)
s.isOn must be(true) s.isOn must be(true)
s.isOff must be(false) s.isOff must be(false)
s.switchOn("hello") must be(false) s.switchOn(()) must be(false)
s.isOn must be(true) s.isOn must be(true)
s.isOff must be(false) s.isOff must be(false)
s.switchOff("hello") must be(true) s.switchOff(()) must be(true)
s.isOff must be(true) s.isOff must be(true)
s.isOn must be(false) s.isOn must be(false)
s.switchOff("hello") must be(false) s.switchOff(()) must be(false)
s.isOff must be(true) s.isOff must be(true)
s.isOn must be(false) s.isOn must be(false)
} }
@ -44,34 +44,34 @@ class SwitchSpec extends WordSpec with MustMatchers {
val s = new Switch(false) val s = new Switch(false)
s.ifOffYield("yes") must be(Some("yes")) s.ifOffYield("yes") must be(Some("yes"))
s.ifOnYield("no") must be(None) s.ifOnYield("no") must be(None)
s.ifOff("yes") must be(true) s.ifOff(()) must be(true)
s.ifOn("no") must be(false) s.ifOn(()) must be(false)
s.switchOn() s.switchOn(())
s.ifOnYield("yes") must be(Some("yes")) s.ifOnYield("yes") must be(Some("yes"))
s.ifOffYield("no") must be(None) s.ifOffYield("no") must be(None)
s.ifOn("yes") must be(true) s.ifOn(()) must be(true)
s.ifOff("no") must be(false) s.ifOff(()) must be(false)
} }
"run action with locking" in { "run action with locking" in {
val s = new Switch(false) val s = new Switch(false)
s.whileOffYield("yes") must be(Some("yes")) s.whileOffYield("yes") must be(Some("yes"))
s.whileOnYield("no") must be(None) s.whileOnYield("no") must be(None)
s.whileOff("yes") must be(true) s.whileOff(()) must be(true)
s.whileOn("no") must be(false) s.whileOn(()) must be(false)
s.switchOn() s.switchOn(())
s.whileOnYield("yes") must be(Some("yes")) s.whileOnYield("yes") must be(Some("yes"))
s.whileOffYield("no") must be(None) s.whileOffYield("no") must be(None)
s.whileOn("yes") must be(true) s.whileOn(()) must be(true)
s.whileOff("no") must be(false) s.whileOff(()) must be(false)
} }
"run first or second action depending on state" in { "run first or second action depending on state" in {
val s = new Switch(false) val s = new Switch(false)
s.fold("on")("off") must be("off") s.fold("on")("off") must be("off")
s.switchOn() s.switchOn(())
s.fold("on")("off") must be("on") s.fold("on")("off") must be("on")
} }
@ -80,14 +80,14 @@ class SwitchSpec extends WordSpec with MustMatchers {
s.locked { s.locked {
Thread.sleep(500) Thread.sleep(500)
s.switchOn() s.switchOn(())
s.isOn must be(true) s.isOn must be(true)
} }
val latch = new CountDownLatch(1) val latch = new CountDownLatch(1)
new Thread { new Thread {
override def run(): Unit = { override def run(): Unit = {
s.switchOff() s.switchOff(())
latch.countDown() latch.countDown()
} }
}.start() }.start()

View file

@ -470,7 +470,7 @@ private[akka] class EmptyLocalActorRef(override val provider: ActorRefProvider,
override val path: ActorPath, override val path: ActorPath,
val eventStream: EventStream) extends MinimalActorRef { val eventStream: EventStream) extends MinimalActorRef {
override def isTerminated(): Boolean = true override def isTerminated: Boolean = true
override def sendSystemMessage(message: SystemMessage): Unit = { override def sendSystemMessage(message: SystemMessage): Unit = {
if (Mailbox.debug) println(s"ELAR $path having enqueued $message") if (Mailbox.debug) println(s"ELAR $path having enqueued $message")

View file

@ -329,7 +329,7 @@ private[akka] object SystemGuardian {
* *
* Depending on this class is not supported, only the [[ActorRefProvider]] interface is supported. * Depending on this class is not supported, only the [[ActorRefProvider]] interface is supported.
*/ */
class LocalActorRefProvider private[akka] ( private[akka] class LocalActorRefProvider private[akka] (
_systemName: String, _systemName: String,
override val settings: ActorSystem.Settings, override val settings: ActorSystem.Settings,
val eventStream: EventStream, val eventStream: EventStream,

View file

@ -613,7 +613,7 @@ private[akka] class ContinuousCancellable extends AtomicReference[HWTimeout](Con
case some if (!compareAndSet(some, newTimeout)) swap(newTimeout) case some if (!compareAndSet(some, newTimeout)) swap(newTimeout)
} }
def isCancelled(): Boolean = get().isCancelled() override def isCancelled: Boolean = get().isCancelled()
def cancel(): Boolean = getAndSet(ContinuousCancellable.cancelled).cancel() def cancel(): Boolean = getAndSet(ContinuousCancellable.cancelled).cancel()
} }

View file

@ -248,7 +248,7 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi
private[akka] class TypedActor[R <: AnyRef, T <: R](val proxyVar: AtomVar[R], createInstance: T) extends Actor { private[akka] class TypedActor[R <: AnyRef, T <: R](val proxyVar: AtomVar[R], createInstance: T) extends Actor {
val me = withContext[T](createInstance) val me = withContext[T](createInstance)
override def supervisorStrategy(): SupervisorStrategy = me match { override def supervisorStrategy: SupervisorStrategy = me match {
case l: Supervisor l.supervisorStrategy case l: Supervisor l.supervisorStrategy
case _ super.supervisorStrategy case _ super.supervisorStrategy
} }

View file

@ -74,7 +74,7 @@ private[akka] object MessageDispatcher {
// since this is a compile-time constant, scalac will elide code behind if (MessageDispatcher.debug) (RK checked with 2.9.1) // since this is a compile-time constant, scalac will elide code behind if (MessageDispatcher.debug) (RK checked with 2.9.1)
final val debug = false // Deliberately without type ascription to make it a compile-time constant final val debug = false // Deliberately without type ascription to make it a compile-time constant
lazy val actors = new Index[MessageDispatcher, ActorRef](16, _ compareTo _) lazy val actors = new Index[MessageDispatcher, ActorRef](16, _ compareTo _)
def printActors: Unit = def printActors(): Unit =
if (debug) { if (debug) {
for { for {
d actors.keys d actors.keys
@ -242,7 +242,7 @@ abstract class MessageDispatcher(val prerequisites: DispatcherPrerequisites) ext
/** /**
* After the call to this method, the dispatcher mustn't begin any new message processing for the specified reference * After the call to this method, the dispatcher mustn't begin any new message processing for the specified reference
*/ */
def suspend(actor: ActorCell): Unit = { protected[akka] def suspend(actor: ActorCell): Unit = {
val mbox = actor.mailbox val mbox = actor.mailbox
if ((mbox.actor eq actor) && (mbox.dispatcher eq this)) if ((mbox.actor eq actor) && (mbox.dispatcher eq this))
mbox.suspend() mbox.suspend()
@ -251,7 +251,7 @@ abstract class MessageDispatcher(val prerequisites: DispatcherPrerequisites) ext
/* /*
* After the call to this method, the dispatcher must begin any new message processing for the specified reference * After the call to this method, the dispatcher must begin any new message processing for the specified reference
*/ */
def resume(actor: ActorCell): Unit = { protected[akka] def resume(actor: ActorCell): Unit = {
val mbox = actor.mailbox val mbox = actor.mailbox
if ((mbox.actor eq actor) && (mbox.dispatcher eq this) && mbox.resume()) if ((mbox.actor eq actor) && (mbox.dispatcher eq this) && mbox.resume())
registerForExecution(mbox, false, false) registerForExecution(mbox, false, false)

View file

@ -16,8 +16,6 @@ import scala.util.control.NonFatal
import com.typesafe.config.Config import com.typesafe.config.Config
import scala.concurrent.duration.FiniteDuration import scala.concurrent.duration.FiniteDuration
import akka.actor.DeadLetter import akka.actor.DeadLetter
import akka.dispatch.BoundedMailbox
import akka.dispatch.BoundedDequeBasedMailbox
/** /**
* INTERNAL API * INTERNAL API

View file

@ -276,7 +276,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel,
override def postRestart(reason: Throwable): Unit = override def postRestart(reason: Throwable): Unit =
throw new IllegalStateException("Restarting not supported for connection actors.") throw new IllegalStateException("Restarting not supported for connection actors.")
private[TcpConnection] case class PendingWrite( private[io] case class PendingWrite(
commander: ActorRef, commander: ActorRef,
ack: Any, ack: Any,
remainingData: ByteString, remainingData: ByteString,

View file

@ -77,8 +77,9 @@ private[akka] class RoutedActorCell(_system: ActorSystemImpl, _ref: InternalActo
def applyRoute(sender: ActorRef, message: Any): immutable.Iterable[Destination] = message match { def applyRoute(sender: ActorRef, message: Any): immutable.Iterable[Destination] = message match {
case _: AutoReceivedMessage Destination(sender, self) :: Nil case _: AutoReceivedMessage Destination(sender, self) :: Nil
case CurrentRoutees { sender ! RouterRoutees(_routees); Nil } case CurrentRoutees { sender ! RouterRoutees(_routees); Nil }
case msg if route.isDefinedAt(sender, msg) route(sender, message) case _
case _ Nil val payload = (sender, message)
if (route isDefinedAt payload) route(payload) else Nil
} }
/** /**

View file

@ -57,10 +57,9 @@ object Agent {
* Internal helper method * Internal helper method
*/ */
private final def withinTransaction(run: Runnable): Unit = { private final def withinTransaction(run: Runnable): Unit = {
def dispatch = updater.execute(run)
Txn.findCurrent match { Txn.findCurrent match {
case Some(txn) Txn.afterCommit(status dispatch)(txn) case Some(txn) Txn.afterCommit(_ updater.execute(run))(txn)
case _ dispatch case _ updater.execute(run)
} }
} }

View file

@ -4,6 +4,7 @@ import language.postfixOps
import scala.concurrent.{ Await, Future } import scala.concurrent.{ Await, Future }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.control.NonFatal
import akka.util.Timeout import akka.util.Timeout
import akka.testkit._ import akka.testkit._
import scala.concurrent.stm._ import scala.concurrent.stm._
@ -112,7 +113,7 @@ class AgentSpec extends AkkaSpec {
agent send (_ * 2) agent send (_ * 2)
throw new RuntimeException("Expected failure") throw new RuntimeException("Expected failure")
} }
} catch { case _ } } catch { case NonFatal(_) }
agent send countDown agent send countDown

View file

@ -150,7 +150,7 @@ private[camel] class ProducerRegistrar(activationTracker: ActorRef) extends Acto
try { try {
val endpoint = camelContext.getEndpoint(endpointUri) val endpoint = camelContext.getEndpoint(endpointUri)
val processor = new SendProcessor(endpoint) val processor = new SendProcessor(endpoint)
camelObjects += producer -> (endpoint, processor) camelObjects = camelObjects.updated(producer, endpoint -> processor)
// if this throws, the supervisor stops the producer and de-registers it on termination // if this throws, the supervisor stops the producer and de-registers it on termination
processor.start() processor.start()
producer ! CamelProducerObjects(endpoint, processor) producer ! CamelProducerObjects(endpoint, processor)
@ -159,10 +159,10 @@ private[camel] class ProducerRegistrar(activationTracker: ActorRef) extends Acto
case NonFatal(e) throw new ActorActivationException(producer, e) case NonFatal(e) throw new ActorActivationException(producer, e)
} }
} else { } else {
camelObjects.get(producer).foreach { case (endpoint, processor) producer ! CamelProducerObjects(endpoint, processor) } camelObjects.get(producer) foreach { case (endpoint, processor) producer ! CamelProducerObjects(endpoint, processor) }
} }
case DeRegister(producer) case DeRegister(producer)
camelObjects.get(producer).foreach { camelObjects.get(producer) foreach {
case (_, processor) case (_, processor)
try { try {
camelObjects.get(producer).foreach(_._2.stop()) camelObjects.get(producer).foreach(_._2.stop())

View file

@ -70,8 +70,8 @@ class ConcurrentActivationTest extends WordSpec with MustMatchers with NonShared
} }
val (activatedConsumerNames, activatedProducerNames) = partitionNames(activations) val (activatedConsumerNames, activatedProducerNames) = partitionNames(activations)
val (deactivatedConsumerNames, deactivatedProducerNames) = partitionNames(deactivations) val (deactivatedConsumerNames, deactivatedProducerNames) = partitionNames(deactivations)
assertContainsSameElements(activatedConsumerNames, deactivatedConsumerNames) assertContainsSameElements(activatedConsumerNames -> deactivatedConsumerNames)
assertContainsSameElements(activatedProducerNames, deactivatedProducerNames) assertContainsSameElements(activatedProducerNames -> deactivatedProducerNames)
} finally { } finally {
system.eventStream.publish(TestEvent.UnMute(eventFilter)) system.eventStream.publish(TestEvent.UnMute(eventFilter))
} }
@ -97,7 +97,7 @@ class ConsumerBroadcast(promise: Promise[(Future[List[List[ActorRef]]], Future[L
allDeactivationFutures = allDeactivationFutures :+ deactivationListFuture allDeactivationFutures = allDeactivationFutures :+ deactivationListFuture
context.actorOf(Props(new Registrar(i, number, activationListPromise, deactivationListPromise)), "registrar-" + i) context.actorOf(Props(new Registrar(i, number, activationListPromise, deactivationListPromise)), "registrar-" + i)
} }
promise.success((Future.sequence(allActivationFutures)), Future.sequence(allDeactivationFutures)) promise.success(Future.sequence(allActivationFutures) -> Future.sequence(allDeactivationFutures))
broadcaster = Some(context.actorOf(Props[Registrar] withRouter (BroadcastRouter(routees)), "registrarRouter")) broadcaster = Some(context.actorOf(Props[Registrar] withRouter (BroadcastRouter(routees)), "registrarRouter"))
case reg: Any case reg: Any

View file

@ -282,7 +282,7 @@ object ProducerFeatureTest {
} }
override def postStop() { override def postStop() {
for (msg lastMessage; aref lastSender) context.parent ! (aref, msg) for (msg lastMessage; aref lastSender) context.parent ! ((aref, msg))
super.postStop() super.postStop()
} }
} }

View file

@ -147,7 +147,7 @@ class ActorProducerTest extends TestKit(ActorSystem("test")) with WordSpec with
"asynchronous" when { "asynchronous" when {
def verifyFailureIsSet { def verifyFailureIsSet(): Unit = {
producer.processExchangeAdapter(exchange, asyncCallback) producer.processExchangeAdapter(exchange, asyncCallback)
asyncCallback.awaitCalled() asyncCallback.awaitCalled()
verify(exchange).setFailure(any[FailureResult]) verify(exchange).setFailure(any[FailureResult])
@ -158,7 +158,7 @@ class ActorProducerTest extends TestKit(ActorSystem("test")) with WordSpec with
"consumer actor doesnt exist" must { "consumer actor doesnt exist" must {
"set failure message on exchange" in { "set failure message on exchange" in {
producer = given(actor = null, outCapable = true) producer = given(actor = null, outCapable = true)
verifyFailureIsSet verifyFailureIsSet()
} }
} }
@ -226,7 +226,7 @@ class ActorProducerTest extends TestKit(ActorSystem("test")) with WordSpec with
"consumer actor doesnt exist" must { "consumer actor doesnt exist" must {
"set failure message on exchange" in { "set failure message on exchange" in {
producer = given(actor = null, outCapable = false) producer = given(actor = null, outCapable = false)
verifyFailureIsSet verifyFailureIsSet()
} }
} }
@ -325,7 +325,7 @@ class ActorProducerTest extends TestKit(ActorSystem("test")) with WordSpec with
} }
} }
trait ActorProducerFixture extends MockitoSugar with BeforeAndAfterAll with BeforeAndAfterEach { self: TestKit with MustMatchers with Suite private[camel] trait ActorProducerFixture extends MockitoSugar with BeforeAndAfterAll with BeforeAndAfterEach { self: TestKit with MustMatchers with Suite
var camel: Camel = _ var camel: Camel = _
var exchange: CamelExchangeAdapter = _ var exchange: CamelExchangeAdapter = _
var callback: AsyncCallback = _ var callback: AsyncCallback = _
@ -427,9 +427,7 @@ trait ActorProducerFixture extends MockitoSugar with BeforeAndAfterAll with Befo
} }
def echoActor = system.actorOf(Props(new Actor { def echoActor = system.actorOf(Props(new Actor {
def receive = { def receive = { case msg sender ! "received " + msg }
case msg sender ! "received " + msg
}
}), name = "echoActor") }), name = "echoActor")
} }

View file

@ -26,7 +26,7 @@ object Helpers {
def imp[T: c.WeakTypeTag](c: Context): c.Expr[T] = { def imp[T: c.WeakTypeTag](c: Context): c.Expr[T] = {
import c.universe._ import c.universe._
c.Expr[T](TypeApply(Ident("implicitly"), List(TypeTree().setType(weakTypeOf[T])))) c.Expr[T](TypeApply(Ident(newTermName("implicitly")), List(TypeTree().setType(weakTypeOf[T]))))
} }
def bool(c: Context, b: Boolean): c.Expr[Boolean] = c.Expr[Boolean](c.universe.Literal(c.universe.Constant(b))) def bool(c: Context, b: Boolean): c.Expr[Boolean] = c.Expr[Boolean](c.universe.Literal(c.universe.Constant(b)))

View file

@ -73,7 +73,7 @@ private[akka] class ClusterActorRefProvider(
*/ */
override def useActorOnNode(path: ActorPath, props: Props, deploy: Deploy, supervisor: ActorRef): Unit = { override def useActorOnNode(path: ActorPath, props: Props, deploy: Deploy, supervisor: ActorRef): Unit = {
super.useActorOnNode(path, props, deploy, supervisor) super.useActorOnNode(path, props, deploy, supervisor)
remoteDeploymentWatcher ! (actorFor(path), supervisor) remoteDeploymentWatcher ! ((actorFor(path), supervisor))
} }
} }

View file

@ -229,9 +229,9 @@ private[cluster] case class ClusterHeartbeatSenderState private (
heartbeatRequest: Map[Address, Deadline] = Map.empty) { heartbeatRequest: Map[Address, Deadline] = Map.empty) {
// FIXME can be disabled as optimization // FIXME can be disabled as optimization
assertInvariants assertInvariants()
private def assertInvariants: Unit = { private def assertInvariants(): Unit = {
val currentAndEnding = current.intersect(ending.keySet) val currentAndEnding = current.intersect(ending.keySet)
require(currentAndEnding.isEmpty, require(currentAndEnding.isEmpty,
s"Same nodes in current and ending not allowed, got [${currentAndEnding}]") s"Same nodes in current and ending not allowed, got [${currentAndEnding}]")

View file

@ -63,9 +63,9 @@ private[cluster] case class Gossip(
with Versioned[Gossip] { with Versioned[Gossip] {
// FIXME can be disabled as optimization // FIXME can be disabled as optimization
assertInvariants assertInvariants()
private def assertInvariants: Unit = { private def assertInvariants(): Unit = {
val unreachableAndLive = members.intersect(overview.unreachable) val unreachableAndLive = members.intersect(overview.unreachable)
if (unreachableAndLive.nonEmpty) if (unreachableAndLive.nonEmpty)
throw new IllegalArgumentException("Same nodes in both members and unreachable is not allowed, got [%s]" throw new IllegalArgumentException("Same nodes in both members and unreachable is not allowed, got [%s]"

View file

@ -317,7 +317,7 @@ abstract class MixMetricsSelectorBase(selectors: immutable.IndexedSeq[CapacityMe
combined.foldLeft(Map.empty[Address, (Double, Int)].withDefaultValue((0.0, 0))) { combined.foldLeft(Map.empty[Address, (Double, Int)].withDefaultValue((0.0, 0))) {
case (acc, (address, capacity)) case (acc, (address, capacity))
val (sum, count) = acc(address) val (sum, count) = acc(address)
acc + (address -> (sum + capacity, count + 1)) acc + (address -> ((sum + capacity, count + 1)))
}.map { }.map {
case (addr, (sum, count)) (addr -> sum / count) case (addr, (sum, count)) (addr -> sum / count)
} }

View file

@ -31,7 +31,7 @@ class ClusterMetricsMultiJvmNode5 extends ClusterMetricsSpec
abstract class ClusterMetricsSpec extends MultiNodeSpec(ClusterMetricsMultiJvmSpec) with MultiNodeClusterSpec { abstract class ClusterMetricsSpec extends MultiNodeSpec(ClusterMetricsMultiJvmSpec) with MultiNodeClusterSpec {
import ClusterMetricsMultiJvmSpec._ import ClusterMetricsMultiJvmSpec._
def isSigar(collector: MetricsCollector): Boolean = collector.isInstanceOf[SigarMetricsCollector] private[cluster] def isSigar(collector: MetricsCollector): Boolean = collector.isInstanceOf[SigarMetricsCollector]
"Cluster metrics" must { "Cluster metrics" must {
"periodically collect metrics on each node, publish ClusterMetricsChanged to the event stream, " + "periodically collect metrics on each node, publish ClusterMetricsChanged to the event stream, " +

View file

@ -51,7 +51,7 @@ import akka.testkit.TestEvent._
* 8. while nodes are removed remote death watch is also exercised * 8. while nodes are removed remote death watch is also exercised
* 9. while nodes are removed a few cluster aware routers are also working * 9. while nodes are removed a few cluster aware routers are also working
*/ */
object StressMultiJvmSpec extends MultiNodeConfig { private[cluster] object StressMultiJvmSpec extends MultiNodeConfig {
// Note that this test uses default configuration, // Note that this test uses default configuration,
// not MultiNodeClusterSpec.clusterConfig // not MultiNodeClusterSpec.clusterConfig
@ -521,14 +521,14 @@ object StressMultiJvmSpec extends MultiNodeConfig {
log.info("Creating [{}] actors in a tree structure of [{}] levels and each actor has [{}] children", log.info("Creating [{}] actors in a tree structure of [{}] levels and each actor has [{}] children",
totalActors, levels, width) totalActors, levels, width)
val tree = context.actorOf(Props(new TreeNode(levels, width)), "tree") val tree = context.actorOf(Props(new TreeNode(levels, width)), "tree")
tree forward (idx, SimpleJob(id, payload)) tree forward ((idx, SimpleJob(id, payload)))
context.become(treeWorker(tree)) context.become(treeWorker(tree))
} }
def treeWorker(tree: ActorRef): Receive = { def treeWorker(tree: ActorRef): Receive = {
case SimpleJob(id, payload) sender ! Ack(id) case SimpleJob(id, payload) sender ! Ack(id)
case TreeJob(id, payload, idx, _, _) case TreeJob(id, payload, idx, _, _)
tree forward (idx, SimpleJob(id, payload)) tree forward ((idx, SimpleJob(id, payload)))
} }
} }
@ -539,7 +539,7 @@ object StressMultiJvmSpec extends MultiNodeConfig {
0 until width map { i context.actorOf(Props(createChild()), name = i.toString) } toVector 0 until width map { i context.actorOf(Props(createChild()), name = i.toString) } toVector
def receive = { def receive = {
case (idx: Int, job: SimpleJob) if idx < width indexedChildren(idx) forward (idx, job) case (idx: Int, job: SimpleJob) if idx < width indexedChildren(idx) forward ((idx, job))
} }
} }
@ -701,7 +701,7 @@ abstract class StressSpec
lazy val statsObserver = system.actorOf(Props[StatsObserver], "statsObserver") lazy val statsObserver = system.actorOf(Props[StatsObserver], "statsObserver")
def awaitClusterResult: Unit = { def awaitClusterResult(): Unit = {
runOn(roles.head) { runOn(roles.head) {
val r = clusterResultAggregator val r = clusterResultAggregator
watch(r) watch(r)
@ -734,7 +734,7 @@ abstract class StressSpec
} }
} }
awaitClusterResult awaitClusterResult()
enterBarrier("join-one-" + step) enterBarrier("join-one-" + step)
} }
@ -754,7 +754,7 @@ abstract class StressSpec
} }
} }
awaitClusterResult awaitClusterResult()
enterBarrier("join-several-" + step) enterBarrier("join-several-" + step)
} }
@ -804,7 +804,7 @@ abstract class StressSpec
} }
enterBarrier("watch-verified-" + step) enterBarrier("watch-verified-" + step)
awaitClusterResult awaitClusterResult()
enterBarrier("remove-one-" + step) enterBarrier("remove-one-" + step)
} }
@ -828,7 +828,7 @@ abstract class StressSpec
awaitMembersUp(currentRoles.size, timeout = remaining) awaitMembersUp(currentRoles.size, timeout = remaining)
} }
} }
awaitClusterResult awaitClusterResult()
enterBarrier("remove-several-" + step) enterBarrier("remove-several-" + step)
} }
@ -885,7 +885,7 @@ abstract class StressSpec
(nextAS, nextAddresses) (nextAS, nextAddresses)
} }
} }
awaitClusterResult awaitClusterResult()
step += 1 step += 1
loop(counter + 1, nextAS, nextAddresses) loop(counter + 1, nextAS, nextAddresses)
@ -936,7 +936,7 @@ abstract class StressSpec
} }
} }
awaitClusterResult awaitClusterResult()
} }
def awaitWorkResult: WorkResult = { def awaitWorkResult: WorkResult = {
@ -983,7 +983,7 @@ abstract class StressSpec
} }
awaitClusterResult awaitClusterResult()
step += 1 step += 1
} }
} }
@ -1004,7 +1004,7 @@ abstract class StressSpec
} }
} }
awaitClusterResult awaitClusterResult()
nbrUsedRoles += size nbrUsedRoles += size
enterBarrier("after-" + step) enterBarrier("after-" + step)

View file

@ -66,7 +66,7 @@ abstract class UnreachableNodeRejoinsClusterSpec(multiNodeConfig: UnreachableNod
lazy val victim = sortedRoles(1) lazy val victim = sortedRoles(1)
var endBarrierNumber = 0 var endBarrierNumber = 0
def endBarrier: Unit = { def endBarrier(): Unit = {
endBarrierNumber += 1 endBarrierNumber += 1
enterBarrier("after_" + endBarrierNumber) enterBarrier("after_" + endBarrierNumber)
} }
@ -75,7 +75,7 @@ abstract class UnreachableNodeRejoinsClusterSpec(multiNodeConfig: UnreachableNod
"reach initial convergence" taggedAs LongRunningTest in { "reach initial convergence" taggedAs LongRunningTest in {
awaitClusterUp(roles: _*) awaitClusterUp(roles: _*)
endBarrier endBarrier()
} }
"mark a node as UNREACHABLE when we pull the network" taggedAs LongRunningTest in { "mark a node as UNREACHABLE when we pull the network" taggedAs LongRunningTest in {
@ -125,7 +125,7 @@ abstract class UnreachableNodeRejoinsClusterSpec(multiNodeConfig: UnreachableNod
} }
} }
endBarrier endBarrier()
} }
"mark the node as DOWN" taggedAs LongRunningTest in { "mark the node as DOWN" taggedAs LongRunningTest in {
@ -139,7 +139,7 @@ abstract class UnreachableNodeRejoinsClusterSpec(multiNodeConfig: UnreachableNod
awaitAssert(clusterView.unreachableMembers must be(Set.empty), 15 seconds) awaitAssert(clusterView.unreachableMembers must be(Set.empty), 15 seconds)
} }
endBarrier endBarrier()
} }
"allow node to REJOIN when the network is plugged back in" taggedAs LongRunningTest in { "allow node to REJOIN when the network is plugged back in" taggedAs LongRunningTest in {
@ -158,7 +158,7 @@ abstract class UnreachableNodeRejoinsClusterSpec(multiNodeConfig: UnreachableNod
awaitMembersUp(roles.size) awaitMembersUp(roles.size)
endBarrier endBarrier()
} }
} }
} }

View file

@ -35,8 +35,8 @@ class ClusterDomainEventSpec extends WordSpec with MustMatchers {
val eUp = Member(Address("akka.tcp", "sys", "e", 2552), Up, eRoles) val eUp = Member(Address("akka.tcp", "sys", "e", 2552), Up, eRoles)
val eDown = Member(Address("akka.tcp", "sys", "e", 2552), Down, eRoles) val eDown = Member(Address("akka.tcp", "sys", "e", 2552), Down, eRoles)
def converge(gossip: Gossip): (Gossip, Set[Address]) = private[cluster] def converge(gossip: Gossip): (Gossip, Set[Address]) =
((gossip, Set.empty[Address]) /: gossip.members) { (gs, m) (gs._1.seen(m.address), gs._2 + m.address) } ((gossip, Set.empty[Address]) /: gossip.members) { case ((gs, as), m) (gs.seen(m.address), as + m.address) }
"Domain events" must { "Domain events" must {

View file

@ -128,5 +128,5 @@ trait MetricsCollectorFactory { this: AkkaSpec ⇒
new JmxMetricsCollector(selfAddress, defaultDecayFactor) new JmxMetricsCollector(selfAddress, defaultDecayFactor)
}.get }.get
def isSigar(collector: MetricsCollector): Boolean = collector.isInstanceOf[SigarMetricsCollector] private[cluster] def isSigar(collector: MetricsCollector): Boolean = collector.isInstanceOf[SigarMetricsCollector]
} }

View file

@ -61,7 +61,7 @@ class JavaLoggerSpec extends AkkaSpec(JavaLoggerSpec.config) {
} }
"log info without stackTrace" in { "log info without stackTrace" in {
producer ! ("{} is the magic number", 3) producer ! (("{} is the magic number", 3))
val record = expectMsgType[logging.LogRecord] val record = expectMsgType[logging.LogRecord]

View file

@ -60,7 +60,7 @@ class DataflowSpec extends AkkaSpec with DefaultTimeout {
val x = Future("Hello") val x = Future("Hello")
val y = x map (_.length) val y = x map (_.length)
val r = flow(x() + " " + y.map(_ / 0).map(_.toString).apply, 100) val r = flow(x() + " " + y.map(_ / 0).map(_.toString).apply)
intercept[java.lang.ArithmeticException](Await.result(r, timeout.duration)) intercept[java.lang.ArithmeticException](Await.result(r, timeout.duration))
} }
@ -74,7 +74,7 @@ class DataflowSpec extends AkkaSpec with DefaultTimeout {
val x = Future(3) val x = Future(3)
val y = (actor ? "Hello").mapTo[Int] val y = (actor ? "Hello").mapTo[Int]
val r = flow(x() + y(), 100) val r = flow(x() + y())
intercept[ClassCastException](Await.result(r, timeout.duration)) intercept[ClassCastException](Await.result(r, timeout.duration))
} }

View file

@ -25,9 +25,9 @@ class DangerousActor extends Actor with ActorLogging {
new CircuitBreaker(context.system.scheduler, new CircuitBreaker(context.system.scheduler,
maxFailures = 5, maxFailures = 5,
callTimeout = 10.seconds, callTimeout = 10.seconds,
resetTimeout = 1.minute).onOpen(notifyMeOnOpen) resetTimeout = 1.minute).onOpen(notifyMeOnOpen())
def notifyMeOnOpen = def notifyMeOnOpen(): Unit =
log.warning("My CircuitBreaker is now open, and will not close for one minute") log.warning("My CircuitBreaker is now open, and will not close for one minute")
//#circuit-breaker-initialization //#circuit-breaker-initialization

View file

@ -564,7 +564,7 @@ public class FutureDocTestBase {
return "foo"; return "foo";
} }
}, ec); }, ec);
Future<String> result = Futures.firstCompletedOf(Arrays.asList(future, delayed), ec); Future<String> result = Futures.firstCompletedOf(Arrays.<Future<String>>asList(future, delayed), ec);
//#after //#after
Await.result(result, Duration.create(2, SECONDS)); Await.result(result, Duration.create(2, SECONDS));
} }

View file

@ -204,7 +204,7 @@ class CounterService extends Actor {
if (backlog.size >= MaxBacklog) if (backlog.size >= MaxBacklog)
throw new ServiceUnavailable( throw new ServiceUnavailable(
"CounterService not available, lack of initial value") "CounterService not available, lack of initial value")
backlog = backlog :+ (sender, msg) backlog :+= (sender -> msg)
} }
} }

View file

@ -7,7 +7,7 @@ import language.postfixOps
import akka.util.Timeout import akka.util.Timeout
object Introduction { object Introduction {
def foo = { def foo(): Unit = {
//#Consumer-mina //#Consumer-mina
import akka.camel.{ CamelMessage, Consumer } import akka.camel.{ CamelMessage, Consumer }
@ -27,7 +27,7 @@ object Introduction {
val mina = system.actorOf(Props[MyEndpoint]) val mina = system.actorOf(Props[MyEndpoint])
//#Consumer-mina //#Consumer-mina
} }
def bar = { def bar(): Unit = {
//#Consumer //#Consumer
import akka.camel.{ CamelMessage, Consumer } import akka.camel.{ CamelMessage, Consumer }
@ -41,7 +41,7 @@ object Introduction {
} }
//#Consumer //#Consumer
} }
def baz = { def baz(): Unit = {
//#Producer //#Producer
import akka.actor.Actor import akka.actor.Actor
import akka.camel.{ Producer, Oneway } import akka.camel.{ Producer, Oneway }

View file

@ -50,7 +50,7 @@ class DataflowDocSpec extends WordSpec with MustMatchers {
val v1, v2 = Promise[Int]() val v1, v2 = Promise[Int]()
flow { flow {
// v1 will become the value of v2 + 10 when v2 gets a value // v1 will become the value of v2 + 10 when v2 gets a value
v1 << v2() + 10 v1 << 10 + v2()
v1() + v2() v1() + v2()
} onComplete println } onComplete println
flow { v2 << 5 } // As you can see, no blocking above! flow { v2 << 5 } // As you can see, no blocking above!

View file

@ -340,12 +340,12 @@ class FutureDocSpec extends AkkaSpec {
def loadPage(s: String) = s def loadPage(s: String) = s
val url = "foo bar" val url = "foo bar"
def log(cause: Throwable) = () def log(cause: Throwable) = ()
def watchSomeTV = () def watchSomeTV(): Unit = ()
//#and-then //#and-then
val result = Future { loadPage(url) } andThen { val result = Future { loadPage(url) } andThen {
case Failure(exception) log(exception) case Failure(exception) log(exception)
} andThen { } andThen {
case _ watchSomeTV case _ watchSomeTV()
} }
result foreach println result foreach println
//#and-then //#and-then

View file

@ -16,7 +16,7 @@ object RouterViaProgramDocSpec {
class ExampleActor1 extends Actor { class ExampleActor1 extends Actor {
def receive = { def receive = {
case m @ Message1(nbr) sender ! (self, m) case m @ Message1(nbr) sender ! ((self, m))
} }
} }

View file

@ -186,7 +186,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender {
val probe1 = TestProbe() val probe1 = TestProbe()
val probe2 = TestProbe() val probe2 = TestProbe()
val actor = system.actorOf(Props[MyDoubleEcho]) val actor = system.actorOf(Props[MyDoubleEcho])
actor ! (probe1.ref, probe2.ref) actor ! ((probe1.ref, probe2.ref))
actor ! "hello" actor ! "hello"
probe1.expectMsg(500 millis, "hello") probe1.expectMsg(500 millis, "hello")
probe2.expectMsg(500 millis, "hello") probe2.expectMsg(500 millis, "hello")

View file

@ -3,6 +3,7 @@ package akka.actor.mailbox.filebased
import language.postfixOps import language.postfixOps
import akka.actor.mailbox._ import akka.actor.mailbox._
import scala.concurrent.duration._
import org.apache.commons.io.FileUtils import org.apache.commons.io.FileUtils
import akka.dispatch.Mailbox import akka.dispatch.Mailbox
@ -27,18 +28,13 @@ class FileBasedMailboxSpec extends DurableMailboxSpec("File", FileBasedMailboxSp
"read the file-based section" in { "read the file-based section" in {
settings.QueuePath must be("file-based") settings.QueuePath must be("file-based")
settings.CircuitBreakerMaxFailures must be(5) settings.CircuitBreakerMaxFailures must be(5)
import scala.concurrent.duration._
settings.CircuitBreakerCallTimeout must be(5 seconds) settings.CircuitBreakerCallTimeout must be(5 seconds)
} }
} }
def isDurableMailbox(m: Mailbox): Boolean = m.messageQueue.isInstanceOf[FileBasedMessageQueue] private[akka] def isDurableMailbox(m: Mailbox): Boolean = m.messageQueue.isInstanceOf[FileBasedMessageQueue]
def clean() { def clean(): Unit = FileUtils.deleteDirectory(new java.io.File(settings.QueuePath))
FileUtils.deleteDirectory(new java.io.File(settings.QueuePath))
}
override def atStartup() { override def atStartup() {
clean() clean()

View file

@ -191,7 +191,7 @@ private[akka] class ClientFSM(name: RoleName, controllerAddr: InetSocketAddress)
case EnterBarrier(barrier, timeout) barrier case EnterBarrier(barrier, timeout) barrier
case GetAddress(node) node.name case GetAddress(node) node.name
} }
stay using d.copy(runningOp = Some(token, sender)) stay using d.copy(runningOp = Some(token -> sender))
case Event(ToServer(op), Data(channel, Some((token, _)))) case Event(ToServer(op), Data(channel, Some((token, _))))
log.error("cannot write {} while waiting for {}", op, token) log.error("cannot write {} while waiting for {}", op, token)
stay stay

View file

@ -109,9 +109,9 @@ class TestTransport(
(_) defaultShutdown, (_) defaultShutdown,
(_) registry.logActivity(ShutdownAttempt(localAddress))) (_) registry.logActivity(ShutdownAttempt(localAddress)))
override def listen: Future[(Address, Promise[AssociationEventListener])] = listenBehavior() override def listen: Future[(Address, Promise[AssociationEventListener])] = listenBehavior(())
override def associate(remoteAddress: Address): Future[AssociationHandle] = associateBehavior(remoteAddress) override def associate(remoteAddress: Address): Future[AssociationHandle] = associateBehavior(remoteAddress)
override def shutdown(): Unit = shutdownBehavior() override def shutdown(): Unit = shutdownBehavior(())
private def defaultWrite(params: (TestAssociationHandle, ByteString)): Future[Boolean] = { private def defaultWrite(params: (TestAssociationHandle, ByteString)): Future[Boolean] = {
registry.getRemoteReadHandlerFor(params._1) match { registry.getRemoteReadHandlerFor(params._1) match {

View file

@ -210,30 +210,29 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) extends A
case AssociateUnderlying(remoteAddress, statusPromise) case AssociateUnderlying(remoteAddress, statusPromise)
wrappedTransport.associate(remoteAddress) onComplete { wrappedTransport.associate(remoteAddress) onComplete {
// Slight modification of pipe, only success is sent, failure is propagated to a separate future // Slight modification of pipe, only success is sent, failure is propagated to a separate future
case Success(handle) self ! (handle, statusPromise) case Success(handle) self ! ((handle, statusPromise))
case Failure(e) statusPromise.failure(e) case Failure(e) statusPromise.failure(e)
} }
// Finished outbound association and got back the handle // Finished outbound association and got back the handle
case (handle: AssociationHandle, statusPromise: Promise[AssociationHandle]) case (handle: AssociationHandle, statusPromise: Promise[AssociationHandle]) //FIXME switch to a real message iso Tuple2
val wrappedHandle = wrapHandle(handle, associationListener, inbound = false) val wrappedHandle = wrapHandle(handle, associationListener, inbound = false)
val naked = nakedAddress(handle.remoteAddress) val naked = nakedAddress(handle.remoteAddress)
val inMode = getInboundMode(naked) val inMode = getInboundMode(naked)
wrappedHandle.outboundThrottleMode.set(getOutboundMode(naked)) wrappedHandle.outboundThrottleMode.set(getOutboundMode(naked))
wrappedHandle.readHandlerPromise.future.map { (_, inMode) } pipeTo wrappedHandle.throttlerActor wrappedHandle.readHandlerPromise.future map { _ -> inMode } pipeTo wrappedHandle.throttlerActor
handleTable ::= naked -> wrappedHandle handleTable ::= naked -> wrappedHandle
statusPromise.success(wrappedHandle) statusPromise.success(wrappedHandle)
case SetThrottle(address, direction, mode) case SetThrottle(address, direction, mode)
val naked = nakedAddress(address) val naked = nakedAddress(address)
throttlingModes += naked -> (mode, direction) throttlingModes = throttlingModes.updated(naked, (mode, direction))
val ok = Future.successful(SetThrottleAck) val ok = Future.successful(SetThrottleAck)
val allAcks = handleTable.map { Future.sequence(handleTable map {
case (`naked`, handle) setMode(handle, mode, direction) case (`naked`, handle) setMode(handle, mode, direction)
case _ ok case _ ok
} }).map(_ SetThrottleAck) pipeTo sender
Future.sequence(allAcks).map(_ SetThrottleAck) pipeTo sender
case ForceDisassociate(address) case ForceDisassociate(address)
val naked = nakedAddress(address) val naked = nakedAddress(address)
handleTable.foreach { handleTable foreach {
case (`naked`, handle) handle.disassociate() case (`naked`, handle) handle.disassociate()
case _ case _
} }

View file

@ -290,10 +290,10 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D
} }
}), "looker") }), "looker")
// child is configured to be deployed on remote-sys (otherSystem) // child is configured to be deployed on remote-sys (otherSystem)
l ! (Props[Echo1], "child") l ! ((Props[Echo1], "child"))
val child = expectMsgType[ActorRef] val child = expectMsgType[ActorRef]
// grandchild is configured to be deployed on RemotingSpec (system) // grandchild is configured to be deployed on RemotingSpec (system)
child ! (Props[Echo1], "grandchild") child ! ((Props[Echo1], "grandchild"))
val grandchild = expectMsgType[ActorRef] val grandchild = expectMsgType[ActorRef]
grandchild.asInstanceOf[ActorRefScope].isLocal must be(true) grandchild.asInstanceOf[ActorRefScope].isLocal must be(true)
grandchild ! 43 grandchild ! 43
@ -313,7 +313,7 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D
child ! PoisonPill child ! PoisonPill
expectMsg("postStop") expectMsg("postStop")
expectMsgType[Terminated].actor must be === child expectMsgType[Terminated].actor must be === child
l ! (Props[Echo1], "child") l ! ((Props[Echo1], "child"))
val child2 = expectMsgType[ActorRef] val child2 = expectMsgType[ActorRef]
child2 ! 45 child2 ! 45
expectMsg(45) expectMsg(45)

View file

@ -54,7 +54,7 @@ object AkkaProtocolStressTest {
losses += seq - maxSeq - 1 losses += seq - maxSeq - 1
maxSeq = seq maxSeq = seq
if (seq > limit * 0.9) { if (seq > limit * 0.9) {
controller ! (maxSeq, losses) controller ! ((maxSeq, losses))
} }
} else { } else {
controller ! s"Received out of order message. Previous: ${maxSeq} Received: ${seq}" controller ! s"Received out of order message. Previous: ${maxSeq} Received: ${seq}"

View file

@ -21,18 +21,18 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout {
"execute default behavior" in { "execute default behavior" in {
val behavior = defaultBehavior val behavior = defaultBehavior
Await.result(behavior(), timeout.duration) == 3 must be(true) Await.result(behavior(()), timeout.duration) must be === 3
} }
"be able to push generic behavior" in { "be able to push generic behavior" in {
val behavior = defaultBehavior val behavior = defaultBehavior
behavior.push((_) Promise.successful(4).future) behavior.push((_) Promise.successful(4).future)
Await.result(behavior(), timeout.duration) must be(4) Await.result(behavior(()), timeout.duration) must be(4)
behavior.push((_) Promise.failed(TestException).future) behavior.push((_) Promise.failed(TestException).future)
behavior().value match { behavior(()).value match {
case Some(Failure(e)) if e eq TestException case Some(Failure(`TestException`))
case _ fail("Expected exception") case _ fail("Expected exception")
} }
} }
@ -41,15 +41,15 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout {
val behavior = defaultBehavior val behavior = defaultBehavior
behavior.pushConstant(5) behavior.pushConstant(5)
Await.result(behavior(), timeout.duration) must be(5) Await.result(behavior(()), timeout.duration) must be(5)
Await.result(behavior(), timeout.duration) must be(5) Await.result(behavior(()), timeout.duration) must be(5)
} }
"be able to push failure behavior" in { "be able to push failure behavior" in {
val behavior = defaultBehavior val behavior = defaultBehavior
behavior.pushError(TestException) behavior.pushError(TestException)
behavior().value match { behavior(()).value match {
case Some(Failure(e)) if e eq TestException case Some(Failure(e)) if e eq TestException
case _ fail("Expected exception") case _ fail("Expected exception")
} }
@ -59,16 +59,16 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout {
val behavior = defaultBehavior val behavior = defaultBehavior
behavior.pushConstant(5) behavior.pushConstant(5)
Await.result(behavior(), timeout.duration) must be(5) Await.result(behavior(()), timeout.duration) must be(5)
behavior.pushConstant(7) behavior.pushConstant(7)
Await.result(behavior(), timeout.duration) must be(7) Await.result(behavior(()), timeout.duration) must be(7)
behavior.pop() behavior.pop()
Await.result(behavior(), timeout.duration) must be(5) Await.result(behavior(()), timeout.duration) must be(5)
behavior.pop() behavior.pop()
Await.result(behavior(), timeout.duration) must be(3) Await.result(behavior(()), timeout.duration) must be(3)
} }
@ -78,13 +78,13 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout {
behavior.pop() behavior.pop()
behavior.pop() behavior.pop()
Await.result(behavior(), timeout.duration) must be(3) Await.result(behavior(()), timeout.duration) must be(3)
} }
"enable delayed completition" in { "enable delayed completition" in {
val behavior = defaultBehavior val behavior = defaultBehavior
val controlPromise = behavior.pushDelayed val controlPromise = behavior.pushDelayed
val f = behavior() val f = behavior(())
f.isCompleted must be(false) f.isCompleted must be(false)
controlPromise.success(()) controlPromise.success(())

View file

@ -111,13 +111,13 @@ abstract class StatsSampleSpec extends MultiNodeSpec(StatsSampleSpecConfig)
//#test-statsService //#test-statsService
"show usage of the statsService from one node" in within(15 seconds) { "show usage of the statsService from one node" in within(15 seconds) {
runOn(second) { runOn(second) {
assertServiceOk assertServiceOk()
} }
testConductor.enter("done-2") testConductor.enter("done-2")
} }
def assertServiceOk: Unit = { def assertServiceOk(): Unit = {
val service = system.actorFor(node(third) / "user" / "statsService") val service = system.actorFor(node(third) / "user" / "statsService")
// eventually the service should be ok, // eventually the service should be ok,
// first attempts might fail because worker actors not started yet // first attempts might fail because worker actors not started yet
@ -135,7 +135,7 @@ abstract class StatsSampleSpec extends MultiNodeSpec(StatsSampleSpecConfig)
//#test-statsService //#test-statsService
"show usage of the statsService from all nodes" in within(15 seconds) { "show usage of the statsService from all nodes" in within(15 seconds) {
assertServiceOk assertServiceOk()
testConductor.enter("done-3") testConductor.enter("done-3")
} }

View file

@ -94,13 +94,13 @@ abstract class StatsSampleJapiSpec extends MultiNodeSpec(StatsSampleJapiSpecConf
"show usage of the statsService from one node" in within(15 seconds) { "show usage of the statsService from one node" in within(15 seconds) {
runOn(second) { runOn(second) {
assertServiceOk assertServiceOk()
} }
testConductor.enter("done-2") testConductor.enter("done-2")
} }
def assertServiceOk: Unit = { def assertServiceOk(): Unit = {
val service = system.actorFor(node(third) / "user" / "statsService") val service = system.actorFor(node(third) / "user" / "statsService")
// eventually the service should be ok, // eventually the service should be ok,
// first attempts might fail because worker actors not started yet // first attempts might fail because worker actors not started yet
@ -117,7 +117,7 @@ abstract class StatsSampleJapiSpec extends MultiNodeSpec(StatsSampleJapiSpecConf
//#test-statsService //#test-statsService
"show usage of the statsService from all nodes" in within(15 seconds) { "show usage of the statsService from all nodes" in within(15 seconds) {
assertServiceOk assertServiceOk()
testConductor.enter("done-3") testConductor.enter("done-3")
} }

View file

@ -84,7 +84,7 @@ abstract class TransformationSampleSpec extends MultiNodeSpec(TransformationSamp
testConductor.enter("backend1-started") testConductor.enter("backend1-started")
runOn(frontend1) { runOn(frontend1) {
assertServiceOk assertServiceOk()
} }
testConductor.enter("frontend1-backend1-ok") testConductor.enter("frontend1-backend1-ok")
@ -105,7 +105,7 @@ abstract class TransformationSampleSpec extends MultiNodeSpec(TransformationSamp
testConductor.enter("all-started") testConductor.enter("all-started")
runOn(frontend1, frontend2) { runOn(frontend1, frontend2) {
assertServiceOk assertServiceOk()
} }
testConductor.enter("all-ok") testConductor.enter("all-ok")
@ -114,7 +114,7 @@ abstract class TransformationSampleSpec extends MultiNodeSpec(TransformationSamp
} }
def assertServiceOk: Unit = { def assertServiceOk(): Unit = {
val transformationFrontend = system.actorFor("akka://" + system.name + "/user/frontend") val transformationFrontend = system.actorFor("akka://" + system.name + "/user/frontend")
// eventually the service should be ok, // eventually the service should be ok,
// backends might not have registered initially // backends might not have registered initially

View file

@ -86,7 +86,7 @@ abstract class TransformationSampleJapiSpec extends MultiNodeSpec(Transformation
testConductor.enter("backend1-started") testConductor.enter("backend1-started")
runOn(frontend1) { runOn(frontend1) {
assertServiceOk assertServiceOk()
} }
testConductor.enter("frontend1-backend1-ok") testConductor.enter("frontend1-backend1-ok")
@ -106,7 +106,7 @@ abstract class TransformationSampleJapiSpec extends MultiNodeSpec(Transformation
testConductor.enter("all-started") testConductor.enter("all-started")
runOn(frontend1, frontend2) { runOn(frontend1, frontend2) {
assertServiceOk assertServiceOk()
} }
testConductor.enter("all-ok") testConductor.enter("all-ok")
@ -115,7 +115,7 @@ abstract class TransformationSampleJapiSpec extends MultiNodeSpec(Transformation
} }
def assertServiceOk: Unit = { def assertServiceOk(): Unit = {
val transformationFrontend = system.actorFor("akka://" + system.name + "/user/frontend") val transformationFrontend = system.actorFor("akka://" + system.name + "/user/frontend")
// eventually the service should be ok, // eventually the service should be ok,
// backends might not have registered initially // backends might not have registered initially

View file

@ -133,9 +133,9 @@ class Hakker(name: String, left: ActorRef, right: ActorRef) extends Actor {
object DiningHakkers { object DiningHakkers {
val system = ActorSystem() val system = ActorSystem()
def main(args: Array[String]): Unit = run def main(args: Array[String]): Unit = run()
def run { def run(): Unit = {
//Create 5 chopsticks //Create 5 chopsticks
val chopsticks = for (i 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i) val chopsticks = for (i 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i)

View file

@ -169,9 +169,9 @@ object DiningHakkersOnFsm {
val system = ActorSystem() val system = ActorSystem()
def main(args: Array[String]): Unit = run def main(args: Array[String]): Unit = run()
def run = { def run(): Unit = {
// Create 5 chopsticks // Create 5 chopsticks
val chopsticks = for (i 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i) val chopsticks = for (i 1 to 5) yield system.actorOf(Props[Chopstick], "Chopstick" + i)
// Create 5 awesome fsm hakkers and assign them their left and right chopstick // Create 5 awesome fsm hakkers and assign them their left and right chopstick

View file

@ -20,9 +20,8 @@ class CreationApplication extends Bootable {
val remoteActor = val remoteActor =
system.actorOf(Props[AdvancedCalculatorActor], "advancedCalculator") system.actorOf(Props[AdvancedCalculatorActor], "advancedCalculator")
def doSomething(op: MathOp) = { def doSomething(op: MathOp): Unit =
localActor ! (remoteActor, op) localActor ! ((remoteActor, op))
}
//#setup //#setup
def startup() { def startup() {

View file

@ -22,9 +22,8 @@ class LookupApplication extends Bootable {
val remoteActor = system.actorFor( val remoteActor = system.actorFor(
"akka.tcp://CalculatorApplication@127.0.0.1:2552/user/simpleCalculator") "akka.tcp://CalculatorApplication@127.0.0.1:2552/user/simpleCalculator")
def doSomething(op: MathOp) = { def doSomething(op: MathOp): Unit =
actor ! (remoteActor, op) actor ! ((remoteActor, op))
}
//#setup //#setup
def startup() { def startup() {

View file

@ -81,7 +81,7 @@ class Slf4jLoggerSpec extends AkkaSpec(Slf4jLoggerSpec.config) with BeforeAndAft
} }
"log info with parameters" in { "log info with parameters" in {
producer ! ("test x={} y={}", 3, 17) producer ! (("test x={} y={}", 3, 17))
awaitCond(outputString.contains("----"), 5 seconds) awaitCond(outputString.contains("----"), 5 seconds)
val s = outputString val s = outputString

View file

@ -48,7 +48,7 @@ private[testkit] class CallingThreadDispatcherQueues extends Extension {
private var lastGC = 0l private var lastGC = 0l
// we have to forget about long-gone threads sometime // we have to forget about long-gone threads sometime
private def gc { private def gc(): Unit = {
queues = (Map.newBuilder[CallingThreadMailbox, Set[WeakReference[MessageQueue]]] /: queues) { queues = (Map.newBuilder[CallingThreadMailbox, Set[WeakReference[MessageQueue]]] /: queues) {
case (m, (k, v)) case (m, (k, v))
val nv = v filter (_.get ne null) val nv = v filter (_.get ne null)
@ -66,7 +66,7 @@ private[testkit] class CallingThreadDispatcherQueues extends Extension {
val now = System.nanoTime val now = System.nanoTime
if (now - lastGC > 1000000000l) { if (now - lastGC > 1000000000l) {
lastGC = now lastGC = now
gc gc()
} }
} }
@ -165,16 +165,14 @@ class CallingThreadDispatcher(
mbox foreach CallingThreadDispatcherQueues(actor.system).unregisterQueues mbox foreach CallingThreadDispatcherQueues(actor.system).unregisterQueues
} }
override def suspend(actor: ActorCell) { protected[akka] override def suspend(actor: ActorCell) {
actor.mailbox match { actor.mailbox match {
case m: CallingThreadMailbox case m: CallingThreadMailbox { m.suspendSwitch.switchOn; m.suspend() }
m.suspendSwitch.switchOn; m.suspend() case m m.systemEnqueue(actor.self, Suspend())
case m
m.systemEnqueue(actor.self, Suspend())
} }
} }
override def resume(actor: ActorCell) { protected[akka] override def resume(actor: ActorCell) {
actor.mailbox match { actor.mailbox match {
case mbox: CallingThreadMailbox case mbox: CallingThreadMailbox
val queue = mbox.queue val queue = mbox.queue

View file

@ -47,7 +47,7 @@ class TestActorRef[T <: Actor](
import TestActorRef.InternalGetActor import TestActorRef.InternalGetActor
override def newActorCell(system: ActorSystemImpl, ref: InternalActorRef, props: Props, supervisor: InternalActorRef): ActorCell = protected override def newActorCell(system: ActorSystemImpl, ref: InternalActorRef, props: Props, supervisor: InternalActorRef): ActorCell =
new ActorCell(system, ref, props, supervisor) { new ActorCell(system, ref, props, supervisor) {
override def autoReceiveMessage(msg: Envelope) { override def autoReceiveMessage(msg: Envelope) {
msg.message match { msg.message match {

View file

@ -38,5 +38,5 @@ class TestBarrier(count: Int) {
} }
} }
def reset = barrier.reset def reset(): Unit = barrier.reset()
} }

View file

@ -788,3 +788,13 @@ private[testkit] abstract class CachingPartialFunction[A, B <: AnyRef] extends s
final def isDefinedAt(x: A): Boolean = try { cache = `match`(x); true } catch { case NoMatch cache = null.asInstanceOf[B]; false } final def isDefinedAt(x: A): Boolean = try { cache = `match`(x); true } catch { case NoMatch cache = null.asInstanceOf[B]; false }
final override def apply(x: A): B = cache final override def apply(x: A): B = cache
} }
/**
* Wrapper for implicit conversion to add dilated function to Duration.
*/
class TestDuration(duration: FiniteDuration) {
def dilated(implicit system: ActorSystem): FiniteDuration = {
// this cast will succeed unless TestTimeFactor is non-finite (which would be a misconfiguration)
(duration * TestKitExtension(system).TestTimeFactor).asInstanceOf[FiniteDuration]
}
}

View file

@ -47,14 +47,4 @@ package object testkit {
* Corresponding Java API is available in TestKit.dilated * Corresponding Java API is available in TestKit.dilated
*/ */
implicit def duration2TestDuration(duration: FiniteDuration) = new TestDuration(duration) implicit def duration2TestDuration(duration: FiniteDuration) = new TestDuration(duration)
/**
* Wrapper for implicit conversion to add dilated function to Duration.
*/
class TestDuration(duration: FiniteDuration) {
def dilated(implicit system: ActorSystem): FiniteDuration = {
// this cast will succeed unless TestTimeFactor is non-finite (which would be a misconfiguration)
(duration * TestKitExtension(system).TestTimeFactor).asInstanceOf[FiniteDuration]
}
}
} }

View file

@ -109,13 +109,9 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA
import TestActorRefSpec._ import TestActorRefSpec._
override def beforeEach { override def beforeEach(): Unit = otherthread = null
otherthread = null
}
private def assertThread { private def assertThread(): Unit = otherthread must (be(null) or equal(thread))
otherthread must (be(null) or equal(thread))
}
"A TestActorRef must be an ActorRef, hence it" must { "A TestActorRef must be an ActorRef, hence it" must {
@ -167,7 +163,7 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA
counter must be(0) counter must be(0)
assertThread assertThread()
} }
"stop when sent a poison pill" in { "stop when sent a poison pill" in {
@ -185,7 +181,7 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA
case WrappedTerminated(Terminated(`a`)) true case WrappedTerminated(Terminated(`a`)) true
} }
a.isTerminated must be(true) a.isTerminated must be(true)
assertThread assertThread()
} }
} }
@ -209,7 +205,7 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA
boss ! "sendKill" boss ! "sendKill"
counter must be(0) counter must be(0)
assertThread assertThread()
} }
} }

View file

@ -77,7 +77,7 @@ class Context(numIoThreads: Int) extends SocketMeta {
def poller: Poller = context.poller def poller: Poller = context.poller
def term: Unit = context.term def term(): Unit = context.term()
} }
/** /**

View file

@ -62,7 +62,7 @@ class ZeroMQExtension(system: ActorSystem) extends Extension {
* @return the [[akka.actor.Props]] * @return the [[akka.actor.Props]]
*/ */
def newSocketProps(socketParameters: SocketOption*): Props = { def newSocketProps(socketParameters: SocketOption*): Props = {
verifyZeroMQVersion verifyZeroMQVersion()
require(socketParameters exists { require(socketParameters exists {
case s: SocketType.ZMQSocketType true case s: SocketType.ZMQSocketType true
case _ false case _ false
@ -239,7 +239,7 @@ class ZeroMQExtension(system: ActorSystem) extends Extension {
def newRepSocket(socketParameters: Array[SocketOption]): ActorRef = newSocket((SocketType.Rep +: socketParameters): _*) def newRepSocket(socketParameters: Array[SocketOption]): ActorRef = newSocket((SocketType.Rep +: socketParameters): _*)
private val zeromqGuardian: ActorRef = { private val zeromqGuardian: ActorRef = {
verifyZeroMQVersion verifyZeroMQVersion()
system.actorOf(Props(new Actor { system.actorOf(Props(new Actor {
import SupervisorStrategy._ import SupervisorStrategy._
@ -257,7 +257,7 @@ class ZeroMQExtension(system: ActorSystem) extends Extension {
}), "zeromq") }), "zeromq")
} }
private def verifyZeroMQVersion = { private def verifyZeroMQVersion(): Unit = {
require( require(
JZMQ.getFullVersion > ZeroMQExtension.minVersion, JZMQ.getFullVersion > ZeroMQExtension.minVersion,
"Unsupported ZeroMQ version: %s, akka needs at least: %s".format(JZMQ.getVersionString, ZeroMQExtension.minVersionString)) "Unsupported ZeroMQ version: %s, akka needs at least: %s".format(JZMQ.getVersionString, ZeroMQExtension.minVersionString))

View file

@ -15,14 +15,14 @@ class ConcurrentSocketActorSpec extends AkkaSpec {
implicit val timeout: Timeout = Timeout(15 seconds) implicit val timeout: Timeout = Timeout(15 seconds)
def checkZeroMQInstallation = def checkZeroMQInstallation() =
try { try {
zmq.version match { zmq.version match {
case ZeroMQVersion(x, y, _) if x >= 3 || (x >= 2 && y >= 1) Unit case ZeroMQVersion(x, y, _) if x >= 3 || (x >= 2 && y >= 1) Unit
case version invalidZeroMQVersion(version) case version invalidZeroMQVersion(version)
} }
} catch { } catch {
case e: LinkageError zeroMQNotInstalled case e: LinkageError zeroMQNotInstalled()
} }
def invalidZeroMQVersion(version: ZeroMQVersion) { def invalidZeroMQVersion(version: ZeroMQVersion) {
@ -30,19 +30,19 @@ class ConcurrentSocketActorSpec extends AkkaSpec {
pending pending
} }
def zeroMQNotInstalled { def zeroMQNotInstalled(): Unit = {
info("WARNING: The tests are not run because ZeroMQ is not installed. Version >= 2.1.x required.") info("WARNING: The tests are not run because ZeroMQ is not installed. Version >= 2.1.x required.")
pending pending
} }
val endpoint = "tcp://127.0.0.1:%s" format { val s = new java.net.ServerSocket(0); try s.getLocalPort finally s.close() } val endpoint = "tcp://127.0.0.1:%s" format { val s = new java.net.ServerSocket(0); try s.getLocalPort finally s.close() }
// this must stay a def for checkZeroMQInstallation to work correctly // this must stay a def for checkZeroMQInstallation() to work correctly
def zmq = ZeroMQExtension(system) def zmq = ZeroMQExtension(system)
"ConcurrentSocketActor" should { "ConcurrentSocketActor" should {
"support pub-sub connections" in { "support pub-sub connections" in {
checkZeroMQInstallation checkZeroMQInstallation()
val subscriberProbe = TestProbe() val subscriberProbe = TestProbe()
val context = Context() val context = Context()
val publisher = zmq.newSocket(SocketType.Pub, context, Bind(endpoint)) val publisher = zmq.newSocket(SocketType.Pub, context, Bind(endpoint))
@ -79,7 +79,7 @@ class ConcurrentSocketActorSpec extends AkkaSpec {
} }
"support req-rep connections" in { "support req-rep connections" in {
checkZeroMQInstallation checkZeroMQInstallation()
val requesterProbe = TestProbe() val requesterProbe = TestProbe()
val replierProbe = TestProbe() val replierProbe = TestProbe()
val context = Context() val context = Context()
@ -106,7 +106,7 @@ class ConcurrentSocketActorSpec extends AkkaSpec {
} }
"should support push-pull connections" in { "should support push-pull connections" in {
checkZeroMQInstallation checkZeroMQInstallation()
val pullerProbe = TestProbe() val pullerProbe = TestProbe()
val context = Context() val context = Context()
val pusher = zmq.newSocket(SocketType.Push, context, Bind(endpoint)) val pusher = zmq.newSocket(SocketType.Push, context, Bind(endpoint))

View file

@ -572,7 +572,7 @@ object AkkaBuild extends Build {
lazy val defaultSettings = baseSettings ++ formatSettings ++ mimaSettings ++ lsSettings ++ Seq( lazy val defaultSettings = baseSettings ++ formatSettings ++ mimaSettings ++ lsSettings ++ Seq(
// compile options // compile options
scalacOptions in Compile ++= Seq("-encoding", "UTF-8", "-target:jvm-1.6", "-deprecation", "-feature", "-unchecked", "-Xlog-reflective-calls", "-Ywarn-adapted-args"), scalacOptions in Compile ++= Seq("-encoding", "UTF-8", "-target:jvm-1.6", "-deprecation", "-feature", "-unchecked", "-Xlog-reflective-calls", "-Xlint"),
javacOptions in Compile ++= Seq("-source", "1.6", "-target", "1.6", "-Xlint:unchecked", "-Xlint:deprecation"), javacOptions in Compile ++= Seq("-source", "1.6", "-target", "1.6", "-Xlint:unchecked", "-Xlint:deprecation"),
// if changing this between binary and full, also change at the bottom of akka-sbt-plugin/sample/project/Build.scala // if changing this between binary and full, also change at the bottom of akka-sbt-plugin/sample/project/Build.scala