Platinum Sponsor REACTIVE(PROGRAMMING ( WITH(AKKA ( 1(LESSONS(LEARNED(1 Daniel Deogun & Daniel Sawano Twitter: @DanielDeogun, @DanielSawano

Who We Are DanielDeogun DanielSawano Omegapoint Stockholm-Gothenburg-Malmoe-Umea-NewYork

Agenda - Akkainanutshell  - Akka&Java  - AkkaandJava8Lambdas  - Domaininfluences  - Lessonslearnedfrombuildingrealsystems with Akka

Akka in a Nutshell http://akka.io/

Akka in a Nutshell Actors [1] By Dickelbers (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

! http://upload.wikimedia.org/wikipedia/commons/0/09/Sweden_postbox.JPG Messages Mailbox [1] ActorSystem Routers

Akka in a Nutshell Actors [1] By Dickelbers (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

! http://upload.wikimedia.org/wikipedia/commons/0/09/Sweden_postbox.JPG Messages Mailbox [1] ActorSystem Routers

Akka in a Nutshell Actors [1] By Dickelbers (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

! http://upload.wikimedia.org/wikipedia/commons/0/09/Sweden_postbox.JPG Messages Mailbox [1] ActorSystem Routers

Akka in a Nutshell Actors [1] By Dickelbers (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

! http://upload.wikimedia.org/wikipedia/commons/0/09/Sweden_postbox.JPG Messages Mailbox [1] ActorSystem Routers

Akka in a Nutshell Actors [1] By Dickelbers (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

! http://upload.wikimedia.org/wikipedia/commons/0/09/Sweden_postbox.JPG Messages Mailbox [1] ActorSystem Routers

Akka in a Nutshell Actors [1] By Dickelbers (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

! http://upload.wikimedia.org/wikipedia/commons/0/09/Sweden_postbox.JPG Messages Mailbox [1] ActorSystem Routers

Our definition of Legacy Code Legacy
ˈ le-g ə -s ē \

“: something that happened in the past or that comes from someone in the past ” !

  • Merriam-Webster

Our definition of Legacy Code Legacy
ˈ le-g ə -s ē \

“: something that happened in the past or that comes from someone in the past ” !

  • Merriam-Webster
  • Deogun-Sawano Legacy Code
    ˈ le-g ə -s ē
    ˈ k ō d\

“: code that does not satisfy the characteristics of a reactive system ”

What is Legacy Code? Characteristicsofareactivesystem,asdefinedbythereactive manifesto: -responsive -scalable -resilient -event-driven reactivemanifesto.org

Java or Scala IwanttobuildanapplicationwithAkka,shouldIuse JavaorScala? Well,itdepends... [1] https://duke.kenai.com/wave/.Midsize/Wave.png.png ! [2] http://www.scala-lang.org/ [1] [2]

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala:

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala: I I

X

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala: I I I I

X X

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala: I I I I I I

X X X

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala: I I I I I I I

X X X X

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala: I I I I I I I I

X X X X X

Java or Scala Pros & Cons AssumewewanttobuildamachineMtosolvea problemPwhere,  Efficiencyisimperative  Sequentialcomputationsshallbeindependent ImplementationofMshallbeplatformindependent Complexityandboilerplatecodeshallbe reduced M’sbehaviorshallbeverifiable TimetoMarketisessentialandrisksshallbe minimized Scoreboard Java: Scala: I I I I I I I I

X X X X X X

Akka All or nothing? Elastic Distributed Decentralized Resilient Akka Supervision Modularization Integration Parallelism Abstractionlevel

Akka All or nothing? Elastic Distributed Decentralized Resilient Akka Supervision Modularization Integration Parallelism Abstractionlevel

Akka All or nothing? Elastic Distributed Decentralized Resilient Akka Supervision Modularization Integration Parallelism Abstractionlevel

Akka All or nothing? Elastic Distributed Decentralized Resilient Akka Supervision Modularization Integration Parallelism Abstractionlevel

Akka All or nothing? Elastic Distributed Decentralized Resilient Akka Supervision Modularization Integration Parallelism Abstractionlevel

Akka All or nothing? Elastic Distributed Decentralized Resilient Akka Supervision Modularization Integration Parallelism Abstractionlevel

Reactive in a Legacy Environment? Blocking Blocking Blocking Blocking A B C D IsitpossibletoreplaceDbyacomponentimplementedwithAkka?

Debugger
Friend or Foe? Weoftengetthequestion: !  “TheasynchronyinAkkamakesitveryhardto usethedebugger,AmIdoingitwrong?”

debugger in
Legacy Design LegacyDesign ObjectA ObjectB ObjectN

debugger in
Legacy Design LegacyDesign ObjectA ObjectB

debugger in
Legacy Design LegacyDesign ObjectA ObjectB ObjectN PlaceabreakpointinNtofindout  -Whichvaluecausedthecrash?  -Whocreatedit?

debugger in

Reactive Design Reactivedesign BreakpointinactorN

Supervision We’rereactive

Supervision ohno I’mblocked butI’mstill pretty

We’rereactive

Supervision Asynchronous

Supervision Asynchronous Failure

Supervision Synchronous Blockingcall

Supervision Synchronous Blockingcall

Supervision Synchronous Blockingcall Sendfailure

Supervision Synchronous Blockingcall Sendfailure

Supervision ! private ActorRef targetActor; ! private ActorRef caller; ! private Timeout timeout; ! private Cancellable timeoutMessage; ! ! @Override ! public SupervisorStrategy supervisorStrategy() { ! return new OneForOneStrategy(0, Duration.Zero(), new Function<Throwable, SupervisorStrategy.Directive>() { ! public SupervisorStrategy.Directive apply(Throwable cause) { ! caller.tell(new Failure(cause), self()); ! return SupervisorStrategy.stop(); ! } ! }); ! } ! ! @Override ! public void onReceive(final Object message) throws Exception { ! if (message instanceof AskParam) { ! AskParam askParam = (AskParam) message; ! timeout = askParam.timeout; ! caller = sender(); ! targetActor = context().actorOf(askParam.props); ! context().watch(targetActor); ! targetActor.forward(askParam.message, context()); ! final Scheduler scheduler = context().system().scheduler(); ! timeoutMessage = scheduler.scheduleOnce(askParam.timeout.duration(), self(), new AskTimeout(), context().dispatcher(), null); ! } ! else if (message instanceof Terminated) { ! sendFailureToCaller(new ActorKilledException("Target actor terminated.")); ! timeoutMessage.cancel(); ! context().stop(self()); ! } ! else if (message instanceof AskTimeout) { ! sendFailureToCaller(new TimeoutException("Target actor timed out after " + timeout.toString())); ! context().stop(self()); ! } ! else { ! unhandled(message); ! } ! } ! ! private void sendFailureToCaller(final Throwable t) { ! caller.tell(new Failure(t), self()); ! }

Supervision - Writelegacycode - UseAkkaactors

Supervision - Writelegacycode - UseAkkaactors Sequentialdoesnotimplysynchronicity

Changing mindset Sequentialdoesnotimply  synchronicity

Changing mindset Sequentialdoesnotimply  synchronicity

Changing mindset Sequentialdoesnotimply  synchronicity

Changing mindset Sequentialdoesnotimply  synchronicity

Loose Coupling? Messages

The Shared Mutable State Trap Keepingstatebetweenmessagesinanactorisextremely dangerousbecauseitmaycauseasharedmutablestate ! ! !

The Shared Mutable State Trap Actor Properties -Onemessagequeue -Onlyonemessageisprocessedatatime -Messagesareprocessedinorderreceived -Anactormaychoosetodivideandconquer ataskbycalling otheractors

The Shared Mutable State Trap Router Actorsmaybegroupedinarouter Properties -Messagesaredistributedamongactors accordingtosomemessagedeliveryscheme,eg RoundRobinorSmallestMailbox ! -Aroutermayreceivealotofmessages

The Shared Mutable State Trap -Astatefulactoris partofa router ! -Ituses divideandconquertosolve itstask Actorwith state Scenario

The Shared Mutable State Trap Actorwith state -Eachmessagerecivedfromthe routerresets thestate ! -Newmessagesare intermixedwith childresponses ! -Hence,wehaveasharedmutable state  Scenario

The Shared Mutable State Trap Solution -Eachrequestsentbytherouter resultsina“Gather”actor ! -TheGatheractorisresponsible forcollectingtheresult ! -AGatheractorisNEVERreused Gatheractor result

Key Take-Aways -It’sveryeasytoaccidentallyfallbacktosequential“thinking” withstate  ! -Oftenonedoesnotrealizethisuntilthesystemisplaced underheavyload  ! -Trytoavoidstate!

Readability ByVarious.Editedby:WHMawandJDredge(Abandonedlibraryclearance.Selfphotographed.)[Publicdomain],viaWikimediaCommons

Implications of  untyped actors ! Akkaactorsareuntyped-bydesign ! ! public void onReceive(Object message)

Implications of  untyped actors ! Akkaactorsareuntyped-bydesign - Readability - Nosupportfrom compiler/IDE ! ! public void onReceive(Object message)

Message Handling V 1.0 ! ! @Override ! public void onReceive(Object message) { ! if (message instanceof SomeMessage) { ! doStuff(); ! } ! else { ! unhandled(message); ! } ! } !

V 1.0 - If-else contd. ! ! @Override ! public void onReceive(Object message) { ! if (message instanceof SomeMessage) { ! doStuff(); ! } ! else if (message instanceof SomeOtherMessage) { ! doSomeOtherStuff(); ! } ! else { ! unhandled(message); ! } ! } !

V 1.0 - If-else mess ! ! @Override ! public void onReceive(Object message) { ! if (message instanceof SomeMessage) { ! doStuff(); ! } ! else if (message instanceof SomeOtherMessage) { ! doSomeOtherStuff(); ! } ! else if (message instanceof YetAnother Message) { ! doEvenMore Stuff(); ! } ! else { ! unhandled(message); ! } ! } !

Evolution of message handling ! ! ! ! @Override ! public void onReceive(Object message) { ! ... ! } ! ! http://upload.wikimedia.org/wikipedia/commons/thumb/6/69/Human_evolution.svg/2000px-Human_evolution.svg.png

V 2.0 - Overloading ! public void onMessage(SomeMessage message) {...} ! ! public void onMessage(SomeOtherMessage message) {...}

V 2.0 - Overloading ! public void onMessage(SomeMessage message) {...} ! ! public void onMessage(SomeOtherMessage message) {...} ! @Override ! public void onReceive(Object message) { ! ... ! ! methods.get(message.getClass()).invoke(this, message); ! ! ... ! } !

V 2.1 - Annotations ! ! class Worker extends BaseActor { !

!

@Response !

public void onMessage(SomeMessage message) {...} ! ! ! public void onMessage(SomeOtherMessage message) {...} ! }

V 3.0 - Contract ! ! ! interface Messages {
! ! void doSomething (SomeMessage message); ! ! void doSomethingElse (SomeOtherMessage message); ! ! } ! ! ! !

V 3.0 - Contract ! ! ! interface Messages {
! ! void doSomething (SomeMessage message); ! ! void doSomethingElse (SomeOtherMessage message); ! ! } ! ! ! ! ! SomeActor extends BaseActor implements Messages {...} !

V 3.0 - Contract ! ! class Worker extends BaseActor implements Messages { !

! ! public void handleResponse (SomeMessage message) {...} ! ! ! public void handleRequest(SomeOtherMessage message) {...} ! ! }

V 3.0 - Contract ! ! BaseActor extends UntypedActor { ! !

@Override ! ! public void preStart() { ! methodDelegate = new MethodDelegate(this); ! } ! ! @Override ! public void onReceive(Object message) { ! if (methodDelegate.onReceive(message)) { ! return; ! } ! unhandled(message); ! } ! } !

Before ! class Worker extends BaseActor implements Messages { !

@Override !

public void onReceive(Object message) { !

if (message instanceof SomeMessage) { !

doStuff(); !

}

!

else if (message instanceof SomeOtherMessage) { !

doSomeOtherStuff(); ! } ! else if (message instanceof YetAnother Message) { ! doEvenMore Stuff(); !

}

!

else { !

unhandled(message); !

}

!

After ! ! class Worker extends BaseActor implements Messages {
! ! public void handleResponse(SomeMessage message) { ! doStuff(); !

} ! ! public void handleRequest(SomeOtherMessage message) { ! doSomeOtherStuff(); ! } ! ! public void process(YetAnotherMessage message) { ! doEvenMoreStuff(); ! } ! } !

Akka & Java 8 Lambdas

  • Duke: https://duke.kenai.com/thumbsup/DukeWithHelmet.png !
  • Lambda: http://en.wikipedia.org/wiki/Lambda_calculus

Warning http://doc.akka.io/docs/akka/2.3.3/java/lambda-actors.html

The Receive Builder ! ! public class MyActor extends AbstractActor { ! public MyActor() { ! receive(ReceiveBuilder. ! match(SomeMessage.class, m -> { ! doStuff(); ! }). ! match(SomeOtherMessage.class, m -> { ! doSomeOtherStuff(); ! }). ! match(YetAnotherMessage.class, m -> { ! yetSomeMoreStuff(); ! }). ! matchAny(this::unhandled). ! build()); ! } ! } !

A Quick Note On Performance - ThepartialfunctionscreatedbytheReceiveBuilder consistofmultiplelambdaexpressionsforevery matchstatement whichmaybehardfortheJVMto optimize ! - Theresultingcodemaynotbeasperformantasthe correspondinguntypedactorversion

Conclusions - Contractstoexplicitlydefinebehaviorworks prettywell - Canbeausefultoolinyourtoolbox - Java8andlambdasprovidesadditionalapproaches - Scalacangivesimilarsupportviatraits&match

Testing Akka Code Interactbysending messages BDD Scenarios Integrationtests

Scenarios CaseA1: Sortanysequenceofnumbersinincreasingorder ! ! Given  asequenceofnumbersindecreasingorder ! When applyingthesortalgorithm  ! Then theresultingsequenceofnumbersisinincreasingorder

The Test ! ! ! ! @Test ! public void case A1() { ! ! given(sequence(9,8,7,6,5,4,3,2,1,0)) ; !

! whenSorting (); !

! thenResultIs(sequence(0,1,2,3,4,5,6,7,8,9) ); ! ! } !

Key Take-Aways - It’spossibletouseAkkainlegacycode - AkkaisScala&Javacompliant - Akkaisatoolkitwithalotofgoodies - Stopwritinglegacycode

Thankyou @DanielDeogun@DanielSawano