SlideShare une entreprise Scribd logo
1  sur  94
Télécharger pour lire hors ligne
Scalability in Scala and Java
        Nadav Wiener
About me
•   Nadav Wiener (@nadavwr)
•   Senior Consultant & Architect
       @ AlphaCSP
•   Following Scala since 2007
Agenda

Akka
The problem with locks
Actors & message passing
High availability & remoting
STM & Transactors
What is Akka?

•   A actor-based concurrency framework
     • Provides solutions for non blocking concurrency


•   Written in Scala, also works in Java
•   Open source (APL)
•   Now releasing 1.0 after 2 years in development

•   Lead developer and founder: Jonas Boner
     • JRockit, AspectWerkz, AspectJ, Terracotta
“Queen of Lapland”




                     5
You may also remember…
                         6
The Problem
Ignorance Is a Bliss



 If (account1.getBalance() > amount) {
   account1.withdraw(amount)
   account2.deposit(amount)
 }




Sewing on a button © Dvortygirl, 17 February 2008.   8
Not an option
if you plan on
having business
So You Use Threads




Coloured Thread © Philippa Willitts, 24 April 2008.   10
But Without Synchronization
You Get Unpredictable Behavior
                                 11
Lock based concurrency requires
us to constantly second guess our
code



                               12
“The definition of insanity is
doing the same thing over and
over again and expecting different
results. “
– Albert Einstein


                                     13
People Are Bad At Thinking Parallel




                                      14
So you synchronize




          With locks?
                        15
locking


          16
Blocking


           17
Lock too little   Lock too much




                                  18
Lock recklessly?




                   19
Using locks recklessly
                         20
Must Think Globally:
  Lock ordering
  Contention
  Everybody’s code




                       22
Knowing shared-state
concurrency != confidence




                            23
Keep those cores busy!
Cores aren’t getting faster
Default thread stack size on AMD64 = 1MB!
Context switching hurts throughput
25
Actors
Shakespeare Programming
       Language
Excerpt from "Hello World" in SPL

Romeo, a young man with a remarkable patience.
Juliet, a likewise young woman of remarkable grace.

            Scene II: The praising of Juliet.

[Enter Juliet]

             Romeo:
               Thou art as sweet as the sum of the sum
               of Hamlet and his horse and his black
               cat! Speak thy mind!

             [Exit Juliet]
Actors have nothing to do with the
Shakespeare Programming Language
Actors




•   Each actor has a message queue
•   Actors accept and choose what to do with
    messages
•   Lightweight & asynchronous
Actors




•   Each actor has a message queue
•   Actors accept and choose what to do with
    messages
•   Lightweight & asynchronous
Actors




•   Each actor has a message queue
•   Actors accept and choose what to do with
    messages
•   Lightweight & asynchronous
Actors




•   Each actor has a message queue
•   Actors accept and choose what to do with
    messages
•   Lightweight & asynchronous
Actors




•   Each actor has a message queue
•   Actors accept and choose what to do with
    messages
•   Lightweight & asynchronous
Actors




•   Each actor has a message queue
•   Actors accept and choose what to do with
    messages
•   Lightweight & asynchronous
Actors




                                                          ~4 threads
              4 cores


•   Actors tend to remain bound to a single thread
•   Actors rarely block, thread can remain active for a   Actors
    long duration
     • Minimizes context switches – throughput                     X millions
•   Akka actors occupy 650 bytes
Benchmark




•   Several actor implementations for Scala – Akka is considered the fastest
Akka Actors
// Java                                         // Scala
public class GreetingActor extends              class GreetingActor extends Actor {
   UntypedActor {
                                                    private var counter = 0
    private int counter = 0;
                                                    def receive = {
    public void onReceive(Object message)
      throws Exception {                                case message => {

        counter++;                                          counter += 1

        // 1) Hello, Juliet                                 // 1) Hello, Juliet
        log.info(                                           log.info(
            counter + ") Hello, " + message);                   counter + ") Hello, " + message)

    }                                                   }
}                                                   }
                                                }
Akka Actors
// Java                                      // Scala
ActorRef Romeo =                             val greetingActor =
     actorOf(GreetingActor.class).start();      actorOf[GreetingActor].start

greetingActor.sendOneWay("Juliet");          greetingActor ! "Juliet“

// 1) Hello, Juliet                          // 1) Hello, Juliet
Akka Actors

•   Once instantiated, actors can be retrieved by id or uuid
     • uuid - generated by runtime, immutable, unique
     • id - user assigned, by default that's the class name



class Romeo extend GreetingActor {
  self.id = "Romeo"
}
actorOf[Romeo].start


val romeo = actorsFor("Romeo").head

romeo ! "Juliet"
Message Passing
Message Passing

•   Let's build a bank with one actor per account, We’ll be able to :
     • Check our balance
     • Deposit money
     • Withdraw money, but only if we have it (balance remains >= 0)


•   We'll start by defining immutable message types:

case class CheckBalance()
case class Deposit(amount: Int)
case class Withdraw(amount: Int)
Message Passing

class BankAccount(private var balance: Int = 0) extends Actor {
 def receive = {
   // …

        case CheckBalance =>
          self.reply_?(balance)

        // …
    }
}
Message Passing

class BankAccount(private var balance: Int = 0) extends Actor {
 def receive = {
   // …

        case Deposit(amount) =>
          balance += amount

        // …
    }
}
Message Passing

class BankAccount(private var balance: Int = 0) extends Actor {
 def receive = {
   // …

        case Withdraw(amount) =>
          balance = (balance - amount) ensuring (_ >= 0)

        // …
    }
}
Message Passing

•   Now let’s make a deposit:

val account = actorOf[BankAccount].start
account ! Deposit(100)

•   But how do we check the account balance?
Bang! Bang Bang!

•   actorRef ! message     - fire and forget
•   actorRef !! message    - send and block (optional timeout) for response
•   actorRef !!! message   - send, reply using future

...Jones Boner promised to stop at "!!!"

Java equivalents:
• ! = sendOneWay
• !! = sendRequestReply
• !!! = sendRequestReplyFuture
Getting Account Balance

val balance = (account !! CheckBalance) match {
 // do stuff with result
}


// or:



val balanceFuture = account !!! CheckBalance // does not block

// ... go do some other stuff ... later:

val balance = balanceFuture.await.result match {
   // do stuff with result
}
Fault Tolerance
Too Big to Fail



                  51
Jenga Architecture




                     52
The harder they fall




                       53
54
Self Healing,
Graceful Recovery




                    55
Supervision Hierarchies

Supervisors: Kind of actors

Fault Handling Strategy: One for One or All for One

Lifecycle: Permanent or Temporary
Fault Handling Strategy:
One For One
One for One


                           All for One,
                           Permanent


                One for One,               Chat Room,
                Temporary                  Permanent

       Romeo,                  Juliet,
       Permanent               Permanent

                                                   59
One for One


                           All for One,
                           Permanent


                One for One,               Chat Room,
                Temporary                  Permanent

       Romeo,                  Juliet,
       Permanent               Permanent

                                                   60
One for One


                           All for One,
                           Permanent


                One for One,               Chat Room,
                Temporary                  Permanent

       Romeo,                  Juliet,
       Permanent               Permanent

                                                   61
One for One


                           All for One,
                           Permanent


                One for One,               Chat Room,
                Temporary                  Permanent

       Romeo,                  Juliet,
       Permanent               Permanent

                                                   62
One for One


                           All for One,
                           Permanent


                One for One,               Chat Room,
                Temporary                  Permanent

       Romeo,                  Juliet,
       Permanent               Permanent

                                                   63
Fault Handling Strategy:
All For One
All for One


                            All For One,
                            Permanent


                 One for One,               Chat Room,
                 Permanent                  Permanent

        Romeo,                  Juliet,
        Temporary               Temporary

                                                    67
All for One


                            All For One,
                            Permanent


                 One for One,               Chat Room,
                 Permanent                  Permanent

        Romeo,                  Juliet,
        Temporary               Temporary

                                                    68
All for One


                            All For One,
                            Permanent


                 One for One,               Chat Room,
                 Permanent                  Permanent

        Romeo,                  Juliet,
        Temporary               Temporary

                                                    69
All for One


                            All For One,
                            Permanent


                 One for One,               Chat Room,
                 Permanent                  Permanent

        Romeo,                  Juliet,
        Temporary               Temporary

                                                    70
All for One


                            All For One,
                            Permanent


                 One for One,               Chat Room,
                 Permanent                  Permanent

        Romeo,                  Juliet,
        Temporary               Temporary

                                                    71
All for One


                            All For One,
                            Permanent


                 One for One,               Chat Room,
                 Permanent                  Permanent

        Romeo,                  Juliet,
        Temporary               Temporary

                                                    72
Supervision, Remoting & HA

val supervisor = Supervisor(SupervisorConfig(

       AllForOneStrategy(

           List(classOf[Exception]), 3, 1000),

           List(Supervise(actorOf[ChatServer], Permanent),
                Supervise(actorOf[ChatServer], Permanent,
                          RemoteAddess("host1", 9000))
       )
))
High Availability

•   You can’t have a highly available
    system on a single computer

•   Luckily Akka supports near-seamless
    remote actors
High Availability

•   Server managed remote actors:

// on host1
RemoteNode.start("host1", 9000)

// register an actor
RemoteNode.register(“romeo", actorOf[GreetingActor])

// on host2
val romeo = RemoteClient.actorFor(“romeo", "host1", 9000)
romero ! “juliet"


•   RemoteClient handles the connection lifecycle for us
•   Clients can also manage server actors, but enabling this might pose a security
    risk
Actor model – a life choice?
High scalability   Assumes state travels
Hgh availability   along the message
Fast               flow
Etc…               Hostile towards shared
                   state.
                   Minds not easily rewired
                   for this!
Brain Transplant
Software Transactional Memory
Rich Hickey
(Clojure)




              Persistent Data Structures
Persistent Data Structures

•   Share common immutable structure and data
•   Copy-on-write semantics:
      val prices = TransactionalMap[String, Double]
      atomic { prices += ("hamburger" -> 20.0) }

•   When “modified”, minimal changes to structure are made to accommodate
    new data




                                                       © Rich Hickey 2009
How many people seated in the
audience?
If I started counting, by the time I
finished…



                  1, 2, 3, 4, 5, …
…the room would be empty
Jonas Boner
Transactors

class BankAccount extends Transactor {


    private val balanceRef = Ref(0)


     def atomically = {
      // ...
         case CheckBalance => self reply_? balance.get
         // ...
     }
}
Transactors

class BankAccount extends Transactor {


    private val balanceRef = Ref(0)


    def atomically = {
     // ...
        case Deposit(amount) =>
          balance alter (_ + amount)
        // ...
    }
}
Transactors

class BankAccount extends Transactor {


    private val balanceRef = Ref(0)


    def atomically = {
     // ...
        case Withdraw(amount) =>
          balance alter (_ - amount) ensuring (_.get >= 0)
        // ...
    }
}
Transactors

Performing a money transfer transactionally:

val tx = Coordinated()

val fromBalance = (from !! tx(CheckBalance())) match {
  balance: Int => balance
}

if (fromBalance >= 50) {
    from ! tx(Withdraw(50))
    to ! tx(Deposit(50))
}
Coordinated Transactions
class Bank extends Actor         {
 private val accounts =
         TransactionalVector[BankAccount]


    def receive = {
     // ...
     case tx @ Coordinated(Join) => {
         tx atomic {
             accounts += self.sender.get
         }
     }
     // ...
}
Coordinated Transactions

class Bank extends Actor         {
    private val accounts = TransactionalVector[BankAccount]


    def receive = {
     // ...
     case tx @ Coordinated(Sum) => {
         val futures = for (account <- accounts) yield
              account !!! tx(CheckBalance)


         val allTheMoney = futures map (_.await.result) sum

         self reply_? allTheMoney
     }
     // ...
}                                                …and then: println (myBank !! Coordinated(Sum))
Takeaways
Knowing shared-state
concurrency != confidence




                            94
References
http://akkasource.org




                        96
http://scalablesolutions.se




                              97
http://alphacsp.com
Questions?
Typed Actors in Java
•   In Java we will usually avoid “untyped” actors, and use POJOs instead:

interface BankAccount {
   Future<Integer> balance();
   void deposit(int amount);
   void withdraw(int amount);
}

class BankAccountImpl extends TypedActor implements BankAccount {

    // Almost a regular POJO
    public Future<Integer> balance() {
       return future(balance);
    }

    // ...
}

Contenu connexe

En vedette

Distributed Transactions in Akka.NET
Distributed Transactions in Akka.NETDistributed Transactions in Akka.NET
Distributed Transactions in Akka.NETpetabridge
 
Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Matt Raible
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akkanartamonov
 
Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014P. Taylor Goetz
 
Storm: distributed and fault-tolerant realtime computation
Storm: distributed and fault-tolerant realtime computationStorm: distributed and fault-tolerant realtime computation
Storm: distributed and fault-tolerant realtime computationnathanmarz
 
Realtime Analytics with Storm and Hadoop
Realtime Analytics with Storm and HadoopRealtime Analytics with Storm and Hadoop
Realtime Analytics with Storm and HadoopDataWorks Summit
 
Apache Storm 0.9 basic training - Verisign
Apache Storm 0.9 basic training - VerisignApache Storm 0.9 basic training - Verisign
Apache Storm 0.9 basic training - VerisignMichael Noll
 
Hadoop Summit Europe 2014: Apache Storm Architecture
Hadoop Summit Europe 2014: Apache Storm ArchitectureHadoop Summit Europe 2014: Apache Storm Architecture
Hadoop Summit Europe 2014: Apache Storm ArchitectureP. Taylor Goetz
 

En vedette (13)

Distributed Transactions in Akka.NET
Distributed Transactions in Akka.NETDistributed Transactions in Akka.NET
Distributed Transactions in Akka.NET
 
Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
 
Resource Aware Scheduling in Apache Storm
Resource Aware Scheduling in Apache StormResource Aware Scheduling in Apache Storm
Resource Aware Scheduling in Apache Storm
 
Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014
 
Storm: distributed and fault-tolerant realtime computation
Storm: distributed and fault-tolerant realtime computationStorm: distributed and fault-tolerant realtime computation
Storm: distributed and fault-tolerant realtime computation
 
Realtime Analytics with Storm and Hadoop
Realtime Analytics with Storm and HadoopRealtime Analytics with Storm and Hadoop
Realtime Analytics with Storm and Hadoop
 
Yahoo compares Storm and Spark
Yahoo compares Storm and SparkYahoo compares Storm and Spark
Yahoo compares Storm and Spark
 
Apache Storm 0.9 basic training - Verisign
Apache Storm 0.9 basic training - VerisignApache Storm 0.9 basic training - Verisign
Apache Storm 0.9 basic training - Verisign
 
Hadoop Summit Europe 2014: Apache Storm Architecture
Hadoop Summit Europe 2014: Apache Storm ArchitectureHadoop Summit Europe 2014: Apache Storm Architecture
Hadoop Summit Europe 2014: Apache Storm Architecture
 

Dernier

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Dernier (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Akka -- Scalability in Scala and Java

  • 1. Scalability in Scala and Java Nadav Wiener
  • 2. About me • Nadav Wiener (@nadavwr) • Senior Consultant & Architect @ AlphaCSP • Following Scala since 2007
  • 3. Agenda Akka The problem with locks Actors & message passing High availability & remoting STM & Transactors
  • 4. What is Akka? • A actor-based concurrency framework • Provides solutions for non blocking concurrency • Written in Scala, also works in Java • Open source (APL) • Now releasing 1.0 after 2 years in development • Lead developer and founder: Jonas Boner • JRockit, AspectWerkz, AspectJ, Terracotta
  • 6. You may also remember… 6
  • 8. Ignorance Is a Bliss If (account1.getBalance() > amount) { account1.withdraw(amount) account2.deposit(amount) } Sewing on a button © Dvortygirl, 17 February 2008. 8
  • 9. Not an option if you plan on having business
  • 10. So You Use Threads Coloured Thread © Philippa Willitts, 24 April 2008. 10
  • 11. But Without Synchronization You Get Unpredictable Behavior 11
  • 12. Lock based concurrency requires us to constantly second guess our code 12
  • 13. “The definition of insanity is doing the same thing over and over again and expecting different results. “ – Albert Einstein 13
  • 14. People Are Bad At Thinking Parallel 14
  • 15. So you synchronize With locks? 15
  • 16. locking 16
  • 17. Blocking 17
  • 18. Lock too little Lock too much 18
  • 21. Must Think Globally: Lock ordering Contention Everybody’s code 22
  • 23. Keep those cores busy! Cores aren’t getting faster Default thread stack size on AMD64 = 1MB! Context switching hurts throughput
  • 24. 25
  • 27. Excerpt from "Hello World" in SPL Romeo, a young man with a remarkable patience. Juliet, a likewise young woman of remarkable grace. Scene II: The praising of Juliet. [Enter Juliet] Romeo: Thou art as sweet as the sum of the sum of Hamlet and his horse and his black cat! Speak thy mind! [Exit Juliet]
  • 28. Actors have nothing to do with the Shakespeare Programming Language
  • 29. Actors • Each actor has a message queue • Actors accept and choose what to do with messages • Lightweight & asynchronous
  • 30. Actors • Each actor has a message queue • Actors accept and choose what to do with messages • Lightweight & asynchronous
  • 31. Actors • Each actor has a message queue • Actors accept and choose what to do with messages • Lightweight & asynchronous
  • 32. Actors • Each actor has a message queue • Actors accept and choose what to do with messages • Lightweight & asynchronous
  • 33. Actors • Each actor has a message queue • Actors accept and choose what to do with messages • Lightweight & asynchronous
  • 34. Actors • Each actor has a message queue • Actors accept and choose what to do with messages • Lightweight & asynchronous
  • 35. Actors ~4 threads 4 cores • Actors tend to remain bound to a single thread • Actors rarely block, thread can remain active for a Actors long duration • Minimizes context switches – throughput X millions • Akka actors occupy 650 bytes
  • 36. Benchmark • Several actor implementations for Scala – Akka is considered the fastest
  • 37. Akka Actors // Java // Scala public class GreetingActor extends class GreetingActor extends Actor { UntypedActor { private var counter = 0 private int counter = 0; def receive = { public void onReceive(Object message) throws Exception { case message => { counter++; counter += 1 // 1) Hello, Juliet // 1) Hello, Juliet log.info( log.info( counter + ") Hello, " + message); counter + ") Hello, " + message) } } } } }
  • 38. Akka Actors // Java // Scala ActorRef Romeo = val greetingActor = actorOf(GreetingActor.class).start(); actorOf[GreetingActor].start greetingActor.sendOneWay("Juliet"); greetingActor ! "Juliet“ // 1) Hello, Juliet // 1) Hello, Juliet
  • 39. Akka Actors • Once instantiated, actors can be retrieved by id or uuid • uuid - generated by runtime, immutable, unique • id - user assigned, by default that's the class name class Romeo extend GreetingActor { self.id = "Romeo" } actorOf[Romeo].start val romeo = actorsFor("Romeo").head romeo ! "Juliet"
  • 41. Message Passing • Let's build a bank with one actor per account, We’ll be able to : • Check our balance • Deposit money • Withdraw money, but only if we have it (balance remains >= 0) • We'll start by defining immutable message types: case class CheckBalance() case class Deposit(amount: Int) case class Withdraw(amount: Int)
  • 42. Message Passing class BankAccount(private var balance: Int = 0) extends Actor { def receive = { // … case CheckBalance => self.reply_?(balance) // … } }
  • 43. Message Passing class BankAccount(private var balance: Int = 0) extends Actor { def receive = { // … case Deposit(amount) => balance += amount // … } }
  • 44. Message Passing class BankAccount(private var balance: Int = 0) extends Actor { def receive = { // … case Withdraw(amount) => balance = (balance - amount) ensuring (_ >= 0) // … } }
  • 45. Message Passing • Now let’s make a deposit: val account = actorOf[BankAccount].start account ! Deposit(100) • But how do we check the account balance?
  • 46. Bang! Bang Bang! • actorRef ! message - fire and forget • actorRef !! message - send and block (optional timeout) for response • actorRef !!! message - send, reply using future ...Jones Boner promised to stop at "!!!" Java equivalents: • ! = sendOneWay • !! = sendRequestReply • !!! = sendRequestReplyFuture
  • 47. Getting Account Balance val balance = (account !! CheckBalance) match { // do stuff with result } // or: val balanceFuture = account !!! CheckBalance // does not block // ... go do some other stuff ... later: val balance = balanceFuture.await.result match { // do stuff with result }
  • 49. Too Big to Fail 51
  • 51. The harder they fall 53
  • 52. 54
  • 54. Supervision Hierarchies Supervisors: Kind of actors Fault Handling Strategy: One for One or All for One Lifecycle: Permanent or Temporary
  • 56. One for One All for One, Permanent One for One, Chat Room, Temporary Permanent Romeo, Juliet, Permanent Permanent 59
  • 57. One for One All for One, Permanent One for One, Chat Room, Temporary Permanent Romeo, Juliet, Permanent Permanent 60
  • 58. One for One All for One, Permanent One for One, Chat Room, Temporary Permanent Romeo, Juliet, Permanent Permanent 61
  • 59. One for One All for One, Permanent One for One, Chat Room, Temporary Permanent Romeo, Juliet, Permanent Permanent 62
  • 60. One for One All for One, Permanent One for One, Chat Room, Temporary Permanent Romeo, Juliet, Permanent Permanent 63
  • 62. All for One All For One, Permanent One for One, Chat Room, Permanent Permanent Romeo, Juliet, Temporary Temporary 67
  • 63. All for One All For One, Permanent One for One, Chat Room, Permanent Permanent Romeo, Juliet, Temporary Temporary 68
  • 64. All for One All For One, Permanent One for One, Chat Room, Permanent Permanent Romeo, Juliet, Temporary Temporary 69
  • 65. All for One All For One, Permanent One for One, Chat Room, Permanent Permanent Romeo, Juliet, Temporary Temporary 70
  • 66. All for One All For One, Permanent One for One, Chat Room, Permanent Permanent Romeo, Juliet, Temporary Temporary 71
  • 67. All for One All For One, Permanent One for One, Chat Room, Permanent Permanent Romeo, Juliet, Temporary Temporary 72
  • 68. Supervision, Remoting & HA val supervisor = Supervisor(SupervisorConfig( AllForOneStrategy( List(classOf[Exception]), 3, 1000), List(Supervise(actorOf[ChatServer], Permanent), Supervise(actorOf[ChatServer], Permanent, RemoteAddess("host1", 9000)) ) ))
  • 69. High Availability • You can’t have a highly available system on a single computer • Luckily Akka supports near-seamless remote actors
  • 70. High Availability • Server managed remote actors: // on host1 RemoteNode.start("host1", 9000) // register an actor RemoteNode.register(“romeo", actorOf[GreetingActor]) // on host2 val romeo = RemoteClient.actorFor(“romeo", "host1", 9000) romero ! “juliet" • RemoteClient handles the connection lifecycle for us • Clients can also manage server actors, but enabling this might pose a security risk
  • 71. Actor model – a life choice?
  • 72. High scalability Assumes state travels Hgh availability along the message Fast flow Etc… Hostile towards shared state. Minds not easily rewired for this!
  • 75. Rich Hickey (Clojure) Persistent Data Structures
  • 76. Persistent Data Structures • Share common immutable structure and data • Copy-on-write semantics: val prices = TransactionalMap[String, Double] atomic { prices += ("hamburger" -> 20.0) } • When “modified”, minimal changes to structure are made to accommodate new data © Rich Hickey 2009
  • 77. How many people seated in the audience?
  • 78. If I started counting, by the time I finished… 1, 2, 3, 4, 5, …
  • 79. …the room would be empty
  • 81. Transactors class BankAccount extends Transactor { private val balanceRef = Ref(0) def atomically = { // ... case CheckBalance => self reply_? balance.get // ... } }
  • 82. Transactors class BankAccount extends Transactor { private val balanceRef = Ref(0) def atomically = { // ... case Deposit(amount) => balance alter (_ + amount) // ... } }
  • 83. Transactors class BankAccount extends Transactor { private val balanceRef = Ref(0) def atomically = { // ... case Withdraw(amount) => balance alter (_ - amount) ensuring (_.get >= 0) // ... } }
  • 84. Transactors Performing a money transfer transactionally: val tx = Coordinated() val fromBalance = (from !! tx(CheckBalance())) match { balance: Int => balance } if (fromBalance >= 50) { from ! tx(Withdraw(50)) to ! tx(Deposit(50)) }
  • 85. Coordinated Transactions class Bank extends Actor { private val accounts = TransactionalVector[BankAccount] def receive = { // ... case tx @ Coordinated(Join) => { tx atomic { accounts += self.sender.get } } // ... }
  • 86. Coordinated Transactions class Bank extends Actor { private val accounts = TransactionalVector[BankAccount] def receive = { // ... case tx @ Coordinated(Sum) => { val futures = for (account <- accounts) yield account !!! tx(CheckBalance) val allTheMoney = futures map (_.await.result) sum self reply_? allTheMoney } // ... } …and then: println (myBank !! Coordinated(Sum))
  • 94. Typed Actors in Java • In Java we will usually avoid “untyped” actors, and use POJOs instead: interface BankAccount { Future<Integer> balance(); void deposit(int amount); void withdraw(int amount); } class BankAccountImpl extends TypedActor implements BankAccount { // Almost a regular POJO public Future<Integer> balance() { return future(balance); } // ... }