SlideShare a Scribd company logo
The Actor ModelTowards Better ConcurrencyBy: DrorBereznitsky1
Warning: Code Examples
The end of Moore law?Shared state concurrencyMessage passing concurrencyActors on the JVMMore concurrency modelsSummaryAgendaAgenda
The End of Moore Law ?
The number of transistors on a chip will double approximately every 18 months Gordon E. Moore, 1965Moore's lawThe End of Moore Law ?
No matter how fast processors get, software finds new ways to eat up the extra speedAndy Giveth, and Bill Taketh away The End of Moore Law ?
Free and regular performance gains, even without releasing new versions or doing anything specialThe Free LunchThe End of Moore Law ?
The End of Moore Law ?The End of Moore Law ?
Hardware crossed a boundary in the early 2000s: chips got big enough, cycle speed got fast enough a signal can no longer reach the whole chip in a clock cycleproblems with heat dissipation  Why You Don’t Have 10GHz TodayThe End of Moore Law ?9
Processor manufacturers have turned towards multi-core processorsCapable of doing multiple calculations in parallel  CPU speeds are likely to stay relatively flat in the near future The Multicore EraThe End of Moore Law ?10
The performance lunch isn’t free any more Want to benefit from the continued throughput advances in new processors?You will need to develop well-written concurrent applicationsThe Concurrency RevolutionThe End of Moore Law ?11
Amdahl’s LawThe End of Moore Law ?GParallelizer12
Shared State Concurrency13
Shared mutable state Locking mechanismShared State ConcurrencyShared State Concurrency
Threads concurrently execute code sectionsContains resources that must be sharedSynchronized in order to guarantee Correct orderingVisibilityData consistencyThreadsShared State Concurrency
The Popular ChoiceShared State ConcurrencyC#C/C++
Why Threads are EvilShared State Concurrencyhttp://www.flickr.com/photos/amagill/235453953/
“Non-trivial multi-threaded programs are incomprehensible to human …”Edward A. Lee, The Problem with Threads  Not Convinced Yet ?Shared State Concurrency
Message Passing Concurrency (Actors)Software Transactional MemoryDataflow ConcurrencyAlternative Concurrency ModelsShared State Concurrency
Message Passing Concurrency
1973, paper by Carl HewittAvoid the problems caused by threading and locking Implemented in Erlang, Oz, OccamMessage Passing concurrencyMessage Passing concurrency
Actors instead of objectsNo shared state between actorsAsynchronous message-passing Mailboxes to buffer incoming messagesKey PrincipalsMessage Passing Concurrency
React to received messages by executing a behavior functioncan only change the state of the actor itself can send messages to other actorsActors never share state and thus never need to compete for locks for access to shared dataActorsMessage Passing Concurrency
Actors exchange data by sending immutable messages Messages are sent asynchronouslyActors do not block waiting for responses to their messagesMessagesMessage Passing Concurrency
Messages buffered in an actor's mailbox A mailbox is a queue with multiple producers and a single consumerAlso known a channel MailboxMessage Passing Concurrency
A pure functional, dynamically typed language invented in 1986 at EricssonDesigned for concurrency, distribution and scalability Actors are part of the language No Mutable stateErlangMessage Passing Concurrency
loop() ->receivehello ->io:format("Hello, World!~n"),loop();goodbye ->		okend.Hello World in ErlangMessage Passing Concurrency
Actors on the JVM
JVM languages actors implementations available forJavaScala Groovy FantomActors on the JVMActors on the JVM
Actor’s GuildAkkaActorFoundryActoromFunctional JavaKilimJetlangJava Actor LibrariesJava Actors
Experimental Java frameworkmake concurrent programming easierAnnotation based approachMessages handlers are implemented as Java methodsUses a request/response pattern for messagesNot a pure Actors implementationNo special pre-processingActors GuildJava Actors
public abstract class HelloActorextends Actor {@Proppublic abstract String getName();@MessagepublicAsyncResult<String> sayHello(String name) {return result(String.format("Hello %s, my name is %s", 				name, getName())););    }}Actors Guild Hello World: Actor ImplementationJava Actors
Agent agent = newDefaultAgent();HelloActor hello = agent.create(HelloActor.class, new Props("name", "Hamlet"));AsyncResult<String> asyncResult = hello.sayHello("Claudius");System.out.println(asyncResult.get());agent.shutdown();Actors Guild Hello World: Actor Usage Java Actors
@Message@Usage(ThreadUsage.IO)publicAsyncResult<Void> writeFile(...) throws Exception {FileOutputStreamfos = newFileOutputStream(name);fos.write(content.getBytes());fos.close();returnnoResult();}   @Message@Usage(ThreadUsage.Waiting)publicAsyncResult<Void> waitForKeyPrompt() throws Exception {System.in.read();returnnoResult();}Thread Usage PatternJava Actors
@Model(ConcurrencyModel.Stateless)classMultiplicatorActorextends Actor {@Message    public AsyncResult<Integer> mul(int a, int b) {return result(a * b);    }   }Concurrency Model AnnotationsJava Actors
Scala ActorsScala ActorsScala actors combine the powers of functional programming along with the flexible type-system of Scala
Encourages shared-nothing process abstractionsmutable state - privateshared state - immutable Asynchronous message passingPattern matching Fork/Join as the underlying implementation Share Nothing, Asynch Message PassingScala Actors
Thread-based actors - each run in its own JVM threadOverhead in case of large amount of actorsfull stack frame suspension (receive)Event-based actors run on the same thread Use a react block instead of a receive block Thread-based vs. Event-based ActorsScala Actors
Lightweight event objectsExecuted on an underlying worker thread poolautomatically resized when all threads block on long running operations Suspension mechanism based on a continuation closure (react)Lightweight Event Based ActorsScala Actors
The Actor and MessagesScala Actorscase class Name(name: String) case class Greet();objectHelloWorldextends Actor { def act = { varmyName = "Incognito"     loop {       react { case Name(name) => myName = name case Greet =>              reply("Hello, my name is " + myName); exit       }     }   } }
object Greetings extends Application {HelloWorld.startHelloWorld ! Name("foo")HelloWorld !? Greet match {case result: String => println(result);  }}Interacting with the ActorScala Actors
Groovy Actors
GPars = Groovy Parallel SystemsFormerly known as GParallelizerHandle tasks concurrently, asynchronously, and distributedConcurrent collection processingActor programming modelDataflow concurrency constructsSafe - an mt-safe reference to mutable stateGParsGroovy Actors
Inspired by the Actors library in ScalaEvent driven actorsconcurrent actors that share a single pooled threadUsing fork/join under the hoodSupports distributed actorsGpars ActorsGroovy Actors
classHelloWorldextendsAbstractPooledActor {  String namevoid act() {    loop {      react {switch (it) {case'hello': println"Hello, my name is $name"; 					break        }      }    }  }}GPars Actors Hello World: Actor ImplementationGroovy Actors
def actor = newHelloWorld(name : "Charlie").start();actor.send('hello')GPars Actors Hello World: Actor UsageGroovy Actors
Actors in the Real World
Ericson AXD 301 switchmillions of calls per ,99.9999999 percent uptimeFacebook chat application70 million concurrent usersRabbitMQhigh-performance AMQP, 400,000 messages per second. Apache CouchDBdistributed, fault-tolerant document-oriented databaseEjabberd XMPP server – jabber.orgErlang Actors in the Real WorldActors in the Real World
Easier to reason aboutHigher abstraction levelEasier to avoidRace conditionsDeadlocksStarvationLive locksDistributed computingActor BenefitsActors in the Real World
Actors don’t work well whenShared state is needed F.e. bank accountNeed to achieve global consensusSynchronous behavior is requiredIt is not always trivial to break the problem into smaller problemsProblems with ActorsActors in the Real World
More Concurrency Models
1995 Nir Shavit and Dan TouitouMemory as a transactional data setAlternative to lock based synchronizationSimilar to database transactionsOptimistic Approacha thread completes modifications to shared memory without regard for what other threads might be doingSoftware Transactional MemoryMore Concurrency Models
Java STM framework by Guy Korland (TAU, GigaSpaces)@Atomic methodsField based accessMore scalable than Object bases.More efficient than word based.No reserved wordsNo need for new compilers (Existing IDEs can be used)Using bytecode instrumentation (ASM)DeuceMore Concurrency Models
public class Bank{private double commission = 0;@Atomic(retries = 64)public void transaction( Account ac1, Account ac2, double 	amount){		ac1.balance -= (amount + commission);		ac2.balance += amount;	}@Atomic	public void update( double value){	   commission += value;	}}Duece ExampleMore Concurrency Models
public void update( double value){   Context context = ContextDelegetor.getContext();for( inti = retries ; i > 0 ; --i){context.init();try{update( value, context);  if(context.commit()) return;      }catch ( TransactionException e ){context.rollback();continue;      }catch ( Throwable t ){if( context.commit()) throw t;      }     }throw new TransactionException();}Deuce Example Under the HoodMore Concurrency Models
ProsPerformance gains on multi processor machinesSimple approach to concurrencyNo deadlocks or livelocksConsTransactions cannot perform any operation that cannot be undoneSTM Pros and ConsMore Concurrency Models
Summary
The free lunch is overApplications must be built for concurrencyShared state concurrency is hardAlternative concurrency modelsMessage passing concurrencyShared Transactional MemorySummarySummary
The free lunch is overState: You're Doing It WrongEdward A. Lee, The Problem with Threads (PDF)  Alex Miller – Actor ConcurrencyDeuce STMResourcesSummary
Thank You :-)

More Related Content

What's hot (20)

PPTX
Akka Fundamentals
Michael Kendra
 
PPTX
Introduction to Akka - Atlanta Java Users Group
Roy Russo
 
PPTX
Akka framework
mitesh_sharma
 
PPTX
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
PPTX
Akka.net versus microsoft orleans
Bill Tulloch
 
PDF
Introduction to the Actor Model
BoldRadius Solutions
 
PDF
Introduction to Akka
Knoldus Inc.
 
PPTX
Actors Set the Stage for Project Orleans
cjmyers
 
PDF
Rethinking the debugger
Iulian Dragos
 
PPTX
Project Orleans - Actor Model framework
Neil Mackenzie
 
PDF
SF Front End Developers - Ember + D3
Ben Lesh
 
PPTX
Akka.Net Overview
Geoffrey Vandiest
 
PPTX
Akka Actors
Dylan Forciea
 
PDF
Awesome Concurrency with Elixir Tasks
Jonathan Magen
 
PPTX
"Walk in a distributed systems park with Orleans" Евгений Бобров
Fwdays
 
PPTX
Life Beyond Rails: Creating Cross Platform Ruby Apps
Tristan Gomez
 
PDF
Invitation to the dark side of Ruby
SATOSHI TAGOMORI
 
PDF
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Tristan Gomez
 
PDF
Maccro Strikes Back
SATOSHI TAGOMORI
 
PDF
Xtext beyond the defaults - how to tackle performance problems
Holger Schill
 
Akka Fundamentals
Michael Kendra
 
Introduction to Akka - Atlanta Java Users Group
Roy Russo
 
Akka framework
mitesh_sharma
 
Developing distributed applications with Akka and Akka Cluster
Konstantin Tsykulenko
 
Akka.net versus microsoft orleans
Bill Tulloch
 
Introduction to the Actor Model
BoldRadius Solutions
 
Introduction to Akka
Knoldus Inc.
 
Actors Set the Stage for Project Orleans
cjmyers
 
Rethinking the debugger
Iulian Dragos
 
Project Orleans - Actor Model framework
Neil Mackenzie
 
SF Front End Developers - Ember + D3
Ben Lesh
 
Akka.Net Overview
Geoffrey Vandiest
 
Akka Actors
Dylan Forciea
 
Awesome Concurrency with Elixir Tasks
Jonathan Magen
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
Fwdays
 
Life Beyond Rails: Creating Cross Platform Ruby Apps
Tristan Gomez
 
Invitation to the dark side of Ruby
SATOSHI TAGOMORI
 
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Tristan Gomez
 
Maccro Strikes Back
SATOSHI TAGOMORI
 
Xtext beyond the defaults - how to tackle performance problems
Holger Schill
 

Similar to The Actor Model - Towards Better Concurrency (20)

ODP
Concurrency on the JVM
Vaclav Pech
 
ODP
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
PDF
Introduction to concurrent programming with akka actors
datamantra
 
PDF
Introduction to concurrent programming with Akka actors
Shashank L
 
KEY
Practical introduction to the actor model
Georgios Gousios
 
PPTX
Reactive Programming using Actor Model in Akka
StephenKoc1
 
ODP
Actors in the Small
Bill La Forge
 
PPTX
Actors drammen
Reidar Sollid
 
PPTX
Oop2011 actor presentation_stal
Michael Stal
 
PDF
Actor Model and C++: what, why and how? (March 2020 Edition)
Yauheni Akhotnikau
 
PPTX
Concurrency Constructs Overview
stasimus
 
PDF
Akka in 100 slides or less
Derek Wyatt
 
PDF
Multithreading and Actors
Diego Pacheco
 
PDF
Introducing Akka
Meetu Maltiar
 
PDF
Actors: Not Just for Movies Anymore
VictorOps
 
KEY
Akka london scala_user_group
Skills Matter
 
PDF
Akka lsug skills matter
Skills Matter
 
PDF
Scaling Web Apps with Akka
Maciej Matyjas
 
PDF
Actor, an elegant model for concurrent and distributed computation
Alessio Coltellacci
 
PDF
A Survey of Concurrency Constructs
Ted Leung
 
Concurrency on the JVM
Vaclav Pech
 
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
Introduction to concurrent programming with akka actors
datamantra
 
Introduction to concurrent programming with Akka actors
Shashank L
 
Practical introduction to the actor model
Georgios Gousios
 
Reactive Programming using Actor Model in Akka
StephenKoc1
 
Actors in the Small
Bill La Forge
 
Actors drammen
Reidar Sollid
 
Oop2011 actor presentation_stal
Michael Stal
 
Actor Model and C++: what, why and how? (March 2020 Edition)
Yauheni Akhotnikau
 
Concurrency Constructs Overview
stasimus
 
Akka in 100 slides or less
Derek Wyatt
 
Multithreading and Actors
Diego Pacheco
 
Introducing Akka
Meetu Maltiar
 
Actors: Not Just for Movies Anymore
VictorOps
 
Akka london scala_user_group
Skills Matter
 
Akka lsug skills matter
Skills Matter
 
Scaling Web Apps with Akka
Maciej Matyjas
 
Actor, an elegant model for concurrent and distributed computation
Alessio Coltellacci
 
A Survey of Concurrency Constructs
Ted Leung
 
Ad

Recently uploaded (20)

PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Python basic programing language for automation
DanialHabibi2
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Ad

The Actor Model - Towards Better Concurrency

  • 1. The Actor ModelTowards Better ConcurrencyBy: DrorBereznitsky1
  • 3. The end of Moore law?Shared state concurrencyMessage passing concurrencyActors on the JVMMore concurrency modelsSummaryAgendaAgenda
  • 4. The End of Moore Law ?
  • 5. The number of transistors on a chip will double approximately every 18 months Gordon E. Moore, 1965Moore's lawThe End of Moore Law ?
  • 6. No matter how fast processors get, software finds new ways to eat up the extra speedAndy Giveth, and Bill Taketh away The End of Moore Law ?
  • 7. Free and regular performance gains, even without releasing new versions or doing anything specialThe Free LunchThe End of Moore Law ?
  • 8. The End of Moore Law ?The End of Moore Law ?
  • 9. Hardware crossed a boundary in the early 2000s: chips got big enough, cycle speed got fast enough a signal can no longer reach the whole chip in a clock cycleproblems with heat dissipation Why You Don’t Have 10GHz TodayThe End of Moore Law ?9
  • 10. Processor manufacturers have turned towards multi-core processorsCapable of doing multiple calculations in parallel CPU speeds are likely to stay relatively flat in the near future The Multicore EraThe End of Moore Law ?10
  • 11. The performance lunch isn’t free any more Want to benefit from the continued throughput advances in new processors?You will need to develop well-written concurrent applicationsThe Concurrency RevolutionThe End of Moore Law ?11
  • 12. Amdahl’s LawThe End of Moore Law ?GParallelizer12
  • 14. Shared mutable state Locking mechanismShared State ConcurrencyShared State Concurrency
  • 15. Threads concurrently execute code sectionsContains resources that must be sharedSynchronized in order to guarantee Correct orderingVisibilityData consistencyThreadsShared State Concurrency
  • 16. The Popular ChoiceShared State ConcurrencyC#C/C++
  • 17. Why Threads are EvilShared State Concurrencyhttp://www.flickr.com/photos/amagill/235453953/
  • 18. “Non-trivial multi-threaded programs are incomprehensible to human …”Edward A. Lee, The Problem with Threads Not Convinced Yet ?Shared State Concurrency
  • 19. Message Passing Concurrency (Actors)Software Transactional MemoryDataflow ConcurrencyAlternative Concurrency ModelsShared State Concurrency
  • 21. 1973, paper by Carl HewittAvoid the problems caused by threading and locking Implemented in Erlang, Oz, OccamMessage Passing concurrencyMessage Passing concurrency
  • 22. Actors instead of objectsNo shared state between actorsAsynchronous message-passing Mailboxes to buffer incoming messagesKey PrincipalsMessage Passing Concurrency
  • 23. React to received messages by executing a behavior functioncan only change the state of the actor itself can send messages to other actorsActors never share state and thus never need to compete for locks for access to shared dataActorsMessage Passing Concurrency
  • 24. Actors exchange data by sending immutable messages Messages are sent asynchronouslyActors do not block waiting for responses to their messagesMessagesMessage Passing Concurrency
  • 25. Messages buffered in an actor's mailbox A mailbox is a queue with multiple producers and a single consumerAlso known a channel MailboxMessage Passing Concurrency
  • 26. A pure functional, dynamically typed language invented in 1986 at EricssonDesigned for concurrency, distribution and scalability Actors are part of the language No Mutable stateErlangMessage Passing Concurrency
  • 27. loop() ->receivehello ->io:format("Hello, World!~n"),loop();goodbye -> okend.Hello World in ErlangMessage Passing Concurrency
  • 29. JVM languages actors implementations available forJavaScala Groovy FantomActors on the JVMActors on the JVM
  • 31. Experimental Java frameworkmake concurrent programming easierAnnotation based approachMessages handlers are implemented as Java methodsUses a request/response pattern for messagesNot a pure Actors implementationNo special pre-processingActors GuildJava Actors
  • 32. public abstract class HelloActorextends Actor {@Proppublic abstract String getName();@MessagepublicAsyncResult<String> sayHello(String name) {return result(String.format("Hello %s, my name is %s", name, getName()));); }}Actors Guild Hello World: Actor ImplementationJava Actors
  • 33. Agent agent = newDefaultAgent();HelloActor hello = agent.create(HelloActor.class, new Props("name", "Hamlet"));AsyncResult<String> asyncResult = hello.sayHello("Claudius");System.out.println(asyncResult.get());agent.shutdown();Actors Guild Hello World: Actor Usage Java Actors
  • 34. @Message@Usage(ThreadUsage.IO)publicAsyncResult<Void> writeFile(...) throws Exception {FileOutputStreamfos = newFileOutputStream(name);fos.write(content.getBytes());fos.close();returnnoResult();} @Message@Usage(ThreadUsage.Waiting)publicAsyncResult<Void> waitForKeyPrompt() throws Exception {System.in.read();returnnoResult();}Thread Usage PatternJava Actors
  • 35. @Model(ConcurrencyModel.Stateless)classMultiplicatorActorextends Actor {@Message public AsyncResult<Integer> mul(int a, int b) {return result(a * b); } }Concurrency Model AnnotationsJava Actors
  • 36. Scala ActorsScala ActorsScala actors combine the powers of functional programming along with the flexible type-system of Scala
  • 37. Encourages shared-nothing process abstractionsmutable state - privateshared state - immutable Asynchronous message passingPattern matching Fork/Join as the underlying implementation Share Nothing, Asynch Message PassingScala Actors
  • 38. Thread-based actors - each run in its own JVM threadOverhead in case of large amount of actorsfull stack frame suspension (receive)Event-based actors run on the same thread Use a react block instead of a receive block Thread-based vs. Event-based ActorsScala Actors
  • 39. Lightweight event objectsExecuted on an underlying worker thread poolautomatically resized when all threads block on long running operations Suspension mechanism based on a continuation closure (react)Lightweight Event Based ActorsScala Actors
  • 40. The Actor and MessagesScala Actorscase class Name(name: String) case class Greet();objectHelloWorldextends Actor { def act = { varmyName = "Incognito" loop { react { case Name(name) => myName = name case Greet => reply("Hello, my name is " + myName); exit } } } }
  • 41. object Greetings extends Application {HelloWorld.startHelloWorld ! Name("foo")HelloWorld !? Greet match {case result: String => println(result); }}Interacting with the ActorScala Actors
  • 43. GPars = Groovy Parallel SystemsFormerly known as GParallelizerHandle tasks concurrently, asynchronously, and distributedConcurrent collection processingActor programming modelDataflow concurrency constructsSafe - an mt-safe reference to mutable stateGParsGroovy Actors
  • 44. Inspired by the Actors library in ScalaEvent driven actorsconcurrent actors that share a single pooled threadUsing fork/join under the hoodSupports distributed actorsGpars ActorsGroovy Actors
  • 45. classHelloWorldextendsAbstractPooledActor { String namevoid act() { loop { react {switch (it) {case'hello': println"Hello, my name is $name"; break } } } }}GPars Actors Hello World: Actor ImplementationGroovy Actors
  • 46. def actor = newHelloWorld(name : "Charlie").start();actor.send('hello')GPars Actors Hello World: Actor UsageGroovy Actors
  • 47. Actors in the Real World
  • 48. Ericson AXD 301 switchmillions of calls per ,99.9999999 percent uptimeFacebook chat application70 million concurrent usersRabbitMQhigh-performance AMQP, 400,000 messages per second. Apache CouchDBdistributed, fault-tolerant document-oriented databaseEjabberd XMPP server – jabber.orgErlang Actors in the Real WorldActors in the Real World
  • 49. Easier to reason aboutHigher abstraction levelEasier to avoidRace conditionsDeadlocksStarvationLive locksDistributed computingActor BenefitsActors in the Real World
  • 50. Actors don’t work well whenShared state is needed F.e. bank accountNeed to achieve global consensusSynchronous behavior is requiredIt is not always trivial to break the problem into smaller problemsProblems with ActorsActors in the Real World
  • 52. 1995 Nir Shavit and Dan TouitouMemory as a transactional data setAlternative to lock based synchronizationSimilar to database transactionsOptimistic Approacha thread completes modifications to shared memory without regard for what other threads might be doingSoftware Transactional MemoryMore Concurrency Models
  • 53. Java STM framework by Guy Korland (TAU, GigaSpaces)@Atomic methodsField based accessMore scalable than Object bases.More efficient than word based.No reserved wordsNo need for new compilers (Existing IDEs can be used)Using bytecode instrumentation (ASM)DeuceMore Concurrency Models
  • 54. public class Bank{private double commission = 0;@Atomic(retries = 64)public void transaction( Account ac1, Account ac2, double amount){ ac1.balance -= (amount + commission); ac2.balance += amount; }@Atomic public void update( double value){ commission += value; }}Duece ExampleMore Concurrency Models
  • 55. public void update( double value){ Context context = ContextDelegetor.getContext();for( inti = retries ; i > 0 ; --i){context.init();try{update( value, context); if(context.commit()) return; }catch ( TransactionException e ){context.rollback();continue; }catch ( Throwable t ){if( context.commit()) throw t; } }throw new TransactionException();}Deuce Example Under the HoodMore Concurrency Models
  • 56. ProsPerformance gains on multi processor machinesSimple approach to concurrencyNo deadlocks or livelocksConsTransactions cannot perform any operation that cannot be undoneSTM Pros and ConsMore Concurrency Models
  • 58. The free lunch is overApplications must be built for concurrencyShared state concurrency is hardAlternative concurrency modelsMessage passing concurrencyShared Transactional MemorySummarySummary
  • 59. The free lunch is overState: You're Doing It WrongEdward A. Lee, The Problem with Threads (PDF) Alex Miller – Actor ConcurrencyDeuce STMResourcesSummary