Introduction to Akka, as presented on May 3 2012 at the Belgian Java User Group (BeJUG). For more details see: http://www.bejug.org/confluenceBeJUG/display/BeJUG/ForkJoin+and+Akka
Demo code can be found at: http://bit.ly/bejug-akka
8. Actors
How to define an actor?
~400 bytes
Create more actors
Send messages
Modify state Local state
Modify behavior Behavior
mailbox
9. Actors
How to define an actor?
class MyFirstActor extends Actor {
var total = 0
def receive = {
case MyMessage(payload) => println(“Received: “ + payload”)
case countMessage: Int => total += countMessage
case _ => println("Unknown message")
}
}
12. Demo
NearestCityActor
NearestCityActor
NearestCityActor
NearestCityActor
RoundRobin Result
Router ListenerActor
Messages with cities Print results
13. Supervision
Hierarchical supervision
Child actors supervised by parent
Trap exceptions and apply recovery
Error Kernel pattern
Actor 1 create child
actor
Actor 2 dangerous
operation
critical
state supervise
Distinguish scratch and critical state
14. Supervision
class GuardianActor extends Actor {
def supervisorStrategy = OneForOneStrategy({
case _:CompanyBankruptException => Stop
case _:InvalidStateException => Restart
case _:ServiceUnavailableException => Resume
case _ => Escalate
}, maxNrOfRetries = 3, 5.seconds)
def receive = {
...
}
}
Actor may implement
preRestart & postRestart
15. Remote actors
Dispatchers for scale-up, remote actors for scala-out
Machine A Machine B
actor2 ! SomeMsg
Actor 1 Actor 2
Netty, Protobuf
Router Actor 3
Actor creation
Supervision
Remote deploy through config (no code change)
16. Remote actors
Creating 10 actors on 2 nodes with a router
akka
{
actor
{
deployment
{
/serviceA/aggregation
{
router
=
"round-‐robin"
nr-‐of-‐instances
=
10
target
{
nodes
=
["akka://app@10.0.0.2:2552",
"akka://app@10.0.0.3:2552"]
}
}
}
}
}
Looking up a remote actor
val
actor
=
context.actorFor("akka://actorSystemName@10.0.0.1:2552/user/actorName")
17. Blocking
Actors lift some ForkJoin restrictions
Remoting possible
Recursive decomposition optional
Fault-tolerant
Still, there are restrictions similar to ForkJoin tasks
No blocking IO
No explicit locking
No shared memory writes
18. Async IO
Based on composable Futures
Serve http
mini akka-Spray
Consume http
async-http-client
Persistence
hammersmith
19. Async IO
Based on Java NIO
Akka IO
Immutable abstractions on top of:
Channels
Streams (Iteratee based)
Bridges (low-level) async IO and actors
20. Async IO
Practical application:
JMeter => 1 user, 1 thread Gatling => 1 user, 1 actor
+ blocking IO + async-http-client
= OutOfMemory errors =
or clustering necessary
time drift in results
21. Async IO
Practical application:
JMeter => 1 user, 1 thread Gatling => 1 user, 1 actor
+ blocking IO + async-http-client
= OutOfMemory errors =
or clustering necessary
time drift in results
22. Is that all?
Finite State Machine Akka TestKit
core
Scheduler Event Bus
modules
23. Is that all?
Typesafe
Console
Commercial
subscription