SlideShare a Scribd company logo
1 of 60
The Actor Model Towards Better Concurrency By: DrorBereznitsky 1
Warning: Code Examples
The end of Moore law? Shared state concurrency Message passing concurrency Actors on the JVM More concurrency models Summary Agenda Agenda
The End of Moore Law ?
The number of transistors on a chip will double approximately every 18 months  Gordon E. Moore, 1965 Moore's law The End of Moore Law ?
No matter how fast processors get, software finds new ways to eat up the extra speed Andy Giveth, and Bill Taketh away  The End of Moore Law ?
Free and regular performance gains, even without releasing new versions or doing anything special The Free Lunch The 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 cycle problems with heat dissipation   Why You Don’t Have 10GHz Today The End of Moore Law ? 9
Processor manufacturers have turned towards multi-core processors Capable of doing multiple calculations in parallel   CPU speeds are likely to stay relatively flat in the near future  The Multicore Era The 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 applications The Concurrency Revolution The End of Moore Law ? 11
Amdahl’s Law The End of Moore Law ? GParallelizer 12
Shared State Concurrency 13
Shared mutable state  Locking mechanism Shared State Concurrency Shared State Concurrency
Threads concurrently execute code sections Contains resources that must be shared Synchronized in order to guarantee  Correct ordering Visibility Data consistency Threads Shared State Concurrency
The Popular Choice Shared State Concurrency C# C/C++
Why Threads are Evil Shared State Concurrency http://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 Memory Dataflow Concurrency Alternative Concurrency Models Shared State Concurrency
Message Passing Concurrency
1973, paper by Carl Hewitt Avoid the problems caused by threading and locking  Implemented in Erlang, Oz, Occam Message Passing concurrency Message Passing concurrency
Actors instead of objects No shared state between actors Asynchronous message-passing  Mailboxes to buffer incoming messages Key Principals Message Passing Concurrency
React to received messages by executing a behavior function can only change the state of the actor itself  can send messages to other actors Actors never share state and thus never need to compete for locks for access to shared data Actors Message Passing Concurrency
Actors exchange data by sending immutable messages  Messages are sent asynchronously Actors do not block waiting for responses to their messages Messages Message Passing Concurrency
Messages buffered in an actor's mailbox  A mailbox is a queue with multiple producers and a single consumer Also known a channel  Mailbox Message Passing Concurrency
A pure functional, dynamically typed language invented in 1986 at Ericsson Designed for concurrency, distribution and scalability  Actors are part of the language  No Mutable state Erlang Message Passing Concurrency
loop() ->receivehello ->io:format("Hello, World!~n"),loop();goodbye ->		okend. Hello World in Erlang Message Passing Concurrency
Actors on the JVM
JVM languages actors implementations available for Java Scala  Groovy  Fantom Actors on the JVM Actors on the JVM
Actor’s Guild Akka ActorFoundry Actorom Functional Java Kilim Jetlang Java Actor Libraries Java Actors
Experimental Java framework make concurrent programming easier Annotation based approach Messages handlers are implemented as Java methods Uses a request/response pattern for messages Not a pure Actors implementation No special pre-processing Actors Guild Java Actors
public abstract class HelloActorextends Actor { @Prop public abstract String getName(); @Message publicAsyncResult<String> sayHello(String name) { return result( String.format("Hello %s, my name is %s",  				name, getName())););     } } Actors Guild Hello World: Actor Implementation Java 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 Pattern Java Actors
@Model(ConcurrencyModel.Stateless) classMultiplicatorActorextends Actor { @Message     public AsyncResult<Integer> mul(int a, int b) { return result(a * b);     }    } Concurrency Model Annotations Java Actors
Scala Actors Scala Actors Scala actors combine the powers of functional programming along with the flexible type-system of Scala
Encourages shared-nothing process abstractions mutable state - private shared state - immutable  Asynchronous message passing Pattern matching  Fork/Join as the underlying implementation  Share Nothing, Asynch Message Passing Scala Actors
Thread-based actors - each run in its own JVM thread Overhead in case of large amount of actors full 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 Actors Scala Actors
Lightweight event objects Executed on an underlying worker thread pool automatically resized when all threads block on long running operations  Suspension mechanism based on a continuation closure (react) Lightweight Event Based Actors Scala Actors
The Actor and Messages Scala Actors case 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.start HelloWorld ! Name("foo") HelloWorld !? Greet match { case result: String => println(result);   } } Interacting with the Actor Scala Actors
Groovy Actors
GPars = Groovy Parallel Systems Formerly known as GParallelizer Handle tasks concurrently, asynchronously, and distributed Concurrent collection processing Actor programming model Dataflow concurrency constructs Safe - an mt-safe reference to mutable state GPars Groovy Actors
Inspired by the Actors library in Scala Event driven actors concurrent actors that share a single pooled thread Using fork/join under the hood Supports distributed actors Gpars Actors Groovy Actors
classHelloWorldextendsAbstractPooledActor {   String name void act() {     loop {       react { switch (it) { case'hello': println"Hello, my name is $name"; 					break         }       }     }   } } GPars Actors Hello World: Actor Implementation Groovy Actors
def actor = newHelloWorld(name : "Charlie").start(); actor.send('hello') GPars Actors Hello World: Actor Usage Groovy Actors
Actors in the Real World
Ericson AXD 301 switch millions of calls per ,99.9999999 percent uptime Facebook chat application 70 million concurrent users RabbitMQ high-performance AMQP, 400,000 messages per second.  Apache CouchDB distributed, fault-tolerant document-oriented database Ejabberd XMPP server – jabber.org Erlang Actors in the Real World Actors in the Real World
Easier to reason about Higher abstraction level Easier to avoid Race conditions Deadlocks Starvation Live locks Distributed computing Actor Benefits Actors in the Real World
Actors don’t work well when Shared state is needed F.e. bank account Need to achieve global consensus Synchronous behavior is required It is not always trivial to break the problem into smaller problems Problems with Actors Actors in the Real World
More Concurrency Models
1995 Nir Shavit and Dan Touitou Memory as a transactional data set Alternative to lock based synchronization Similar to database transactions Optimistic Approach a thread completes modifications to shared memory without regard for what other threads might be doing Software Transactional Memory More Concurrency Models
Java STM framework by Guy Korland (TAU, GigaSpaces) @Atomic methods Field based access More scalable than Object bases. More efficient than word based. No reserved words No need for new compilers (Existing IDEs can be used) Using bytecode instrumentation (ASM) Deuce More 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 Example More 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 Hood More Concurrency Models
Pros Performance gains on multi processor machines Simple approach to concurrency No deadlocks or livelocks Cons Transactions cannot perform any operation that cannot be undone STM Pros and Cons More Concurrency Models
Summary
The free lunch is over Applications must be built for concurrency Shared state concurrency is hard Alternative concurrency models Message passing concurrency Shared Transactional Memory Summary Summary
The free lunch is over State: You're Doing It Wrong Edward A. Lee, The Problem with Threads (PDF)   Alex Miller – Actor Concurrency Deuce STM Resources Summary
Thank You :-)

More Related Content

What's hot

Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupRoy Russo
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterKonstantin Tsykulenko
 
Akka.net versus microsoft orleans
Akka.net versus microsoft orleansAkka.net versus microsoft orleans
Akka.net versus microsoft orleansBill Tulloch
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to AkkaKnoldus Inc.
 
Actors Set the Stage for Project Orleans
Actors Set the Stage for Project OrleansActors Set the Stage for Project Orleans
Actors Set the Stage for Project Orleanscjmyers
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
Project Orleans - Actor Model framework
Project Orleans - Actor Model frameworkProject Orleans - Actor Model framework
Project Orleans - Actor Model frameworkNeil Mackenzie
 
SF Front End Developers - Ember + D3
SF Front End Developers - Ember + D3SF Front End Developers - Ember + D3
SF Front End Developers - Ember + D3Ben Lesh
 
Awesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir TasksAwesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir TasksJonathan Magen
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений БобровFwdays
 
Life Beyond Rails: Creating Cross Platform Ruby Apps
Life Beyond Rails: Creating Cross Platform Ruby AppsLife Beyond Rails: Creating Cross Platform Ruby Apps
Life Beyond Rails: Creating Cross Platform Ruby AppsTristan Gomez
 
Invitation to the dark side of Ruby
Invitation to the dark side of RubyInvitation to the dark side of Ruby
Invitation to the dark side of RubySATOSHI TAGOMORI
 
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsRefactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsTristan Gomez
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problemsHolger Schill
 

What's hot (20)

Akka Fundamentals
Akka FundamentalsAkka Fundamentals
Akka Fundamentals
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Akka.net versus microsoft orleans
Akka.net versus microsoft orleansAkka.net versus microsoft orleans
Akka.net versus microsoft orleans
 
Introduction to the Actor Model
Introduction to the Actor ModelIntroduction to the Actor Model
Introduction to the Actor Model
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Actors Set the Stage for Project Orleans
Actors Set the Stage for Project OrleansActors Set the Stage for Project Orleans
Actors Set the Stage for Project Orleans
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Project Orleans - Actor Model framework
Project Orleans - Actor Model frameworkProject Orleans - Actor Model framework
Project Orleans - Actor Model framework
 
SF Front End Developers - Ember + D3
SF Front End Developers - Ember + D3SF Front End Developers - Ember + D3
SF Front End Developers - Ember + D3
 
Akka.Net Overview
Akka.Net OverviewAkka.Net Overview
Akka.Net Overview
 
Akka Actors
Akka ActorsAkka Actors
Akka Actors
 
Awesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir TasksAwesome Concurrency with Elixir Tasks
Awesome Concurrency with Elixir Tasks
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
Life Beyond Rails: Creating Cross Platform Ruby Apps
Life Beyond Rails: Creating Cross Platform Ruby AppsLife Beyond Rails: Creating Cross Platform Ruby Apps
Life Beyond Rails: Creating Cross Platform Ruby Apps
 
Invitation to the dark side of Ruby
Invitation to the dark side of RubyInvitation to the dark side of Ruby
Invitation to the dark side of Ruby
 
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsRefactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and Patterns
 
Maccro Strikes Back
Maccro Strikes BackMaccro Strikes Back
Maccro Strikes Back
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problems
 

Similar to The Actor Model - Towards Better Concurrency

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency ConstructsTed Leung
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
CrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked dataCrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked dataRaphael do Vale
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overviewstasimus
 
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007Baruch Sadogursky
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than YouRobert Cooper
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On ConcurrencyWill Gage
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Using OTP and gen_server Effectively
Using OTP and gen_server EffectivelyUsing OTP and gen_server Effectively
Using OTP and gen_server EffectivelyKen Pratt
 

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

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency Constructs
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
Modern C++
Modern C++Modern C++
Modern C++
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
G pars
G parsG pars
G pars
 
All of javascript
All of javascriptAll of javascript
All of javascript
 
CrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked dataCrawlerLD - Distributed crawler for linked data
CrawlerLD - Distributed crawler for linked data
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than You
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On Concurrency
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Using OTP and gen_server Effectively
Using OTP and gen_server EffectivelyUsing OTP and gen_server Effectively
Using OTP and gen_server Effectively
 

Recently uploaded

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

The Actor Model - Towards Better Concurrency

  • 1. The Actor Model Towards Better Concurrency By: DrorBereznitsky 1
  • 3. The end of Moore law? Shared state concurrency Message passing concurrency Actors on the JVM More concurrency models Summary Agenda Agenda
  • 4. The End of Moore Law ?
  • 5. The number of transistors on a chip will double approximately every 18 months Gordon E. Moore, 1965 Moore's law The End of Moore Law ?
  • 6. No matter how fast processors get, software finds new ways to eat up the extra speed Andy Giveth, and Bill Taketh away The End of Moore Law ?
  • 7. Free and regular performance gains, even without releasing new versions or doing anything special The Free Lunch The 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 cycle problems with heat dissipation Why You Don’t Have 10GHz Today The End of Moore Law ? 9
  • 10. Processor manufacturers have turned towards multi-core processors Capable of doing multiple calculations in parallel CPU speeds are likely to stay relatively flat in the near future The Multicore Era The 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 applications The Concurrency Revolution The End of Moore Law ? 11
  • 12. Amdahl’s Law The End of Moore Law ? GParallelizer 12
  • 14. Shared mutable state Locking mechanism Shared State Concurrency Shared State Concurrency
  • 15. Threads concurrently execute code sections Contains resources that must be shared Synchronized in order to guarantee Correct ordering Visibility Data consistency Threads Shared State Concurrency
  • 16. The Popular Choice Shared State Concurrency C# C/C++
  • 17. Why Threads are Evil Shared State Concurrency http://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 Memory Dataflow Concurrency Alternative Concurrency Models Shared State Concurrency
  • 21. 1973, paper by Carl Hewitt Avoid the problems caused by threading and locking Implemented in Erlang, Oz, Occam Message Passing concurrency Message Passing concurrency
  • 22. Actors instead of objects No shared state between actors Asynchronous message-passing Mailboxes to buffer incoming messages Key Principals Message Passing Concurrency
  • 23. React to received messages by executing a behavior function can only change the state of the actor itself can send messages to other actors Actors never share state and thus never need to compete for locks for access to shared data Actors Message Passing Concurrency
  • 24. Actors exchange data by sending immutable messages Messages are sent asynchronously Actors do not block waiting for responses to their messages Messages Message Passing Concurrency
  • 25. Messages buffered in an actor's mailbox A mailbox is a queue with multiple producers and a single consumer Also known a channel Mailbox Message Passing Concurrency
  • 26. A pure functional, dynamically typed language invented in 1986 at Ericsson Designed for concurrency, distribution and scalability Actors are part of the language No Mutable state Erlang Message Passing Concurrency
  • 27. loop() ->receivehello ->io:format("Hello, World!~n"),loop();goodbye -> okend. Hello World in Erlang Message Passing Concurrency
  • 29. JVM languages actors implementations available for Java Scala Groovy Fantom Actors on the JVM Actors on the JVM
  • 30. Actor’s Guild Akka ActorFoundry Actorom Functional Java Kilim Jetlang Java Actor Libraries Java Actors
  • 31. Experimental Java framework make concurrent programming easier Annotation based approach Messages handlers are implemented as Java methods Uses a request/response pattern for messages Not a pure Actors implementation No special pre-processing Actors Guild Java Actors
  • 32. public abstract class HelloActorextends Actor { @Prop public abstract String getName(); @Message publicAsyncResult<String> sayHello(String name) { return result( String.format("Hello %s, my name is %s", name, getName()));); } } Actors Guild Hello World: Actor Implementation Java 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 Pattern Java Actors
  • 35. @Model(ConcurrencyModel.Stateless) classMultiplicatorActorextends Actor { @Message public AsyncResult<Integer> mul(int a, int b) { return result(a * b); } } Concurrency Model Annotations Java Actors
  • 36. Scala Actors Scala Actors Scala actors combine the powers of functional programming along with the flexible type-system of Scala
  • 37. Encourages shared-nothing process abstractions mutable state - private shared state - immutable Asynchronous message passing Pattern matching Fork/Join as the underlying implementation Share Nothing, Asynch Message Passing Scala Actors
  • 38. Thread-based actors - each run in its own JVM thread Overhead in case of large amount of actors full 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 Actors Scala Actors
  • 39. Lightweight event objects Executed on an underlying worker thread pool automatically resized when all threads block on long running operations Suspension mechanism based on a continuation closure (react) Lightweight Event Based Actors Scala Actors
  • 40. The Actor and Messages Scala Actors case 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.start HelloWorld ! Name("foo") HelloWorld !? Greet match { case result: String => println(result); } } Interacting with the Actor Scala Actors
  • 43. GPars = Groovy Parallel Systems Formerly known as GParallelizer Handle tasks concurrently, asynchronously, and distributed Concurrent collection processing Actor programming model Dataflow concurrency constructs Safe - an mt-safe reference to mutable state GPars Groovy Actors
  • 44. Inspired by the Actors library in Scala Event driven actors concurrent actors that share a single pooled thread Using fork/join under the hood Supports distributed actors Gpars Actors Groovy Actors
  • 45. classHelloWorldextendsAbstractPooledActor { String name void act() { loop { react { switch (it) { case'hello': println"Hello, my name is $name"; break } } } } } GPars Actors Hello World: Actor Implementation Groovy Actors
  • 46. def actor = newHelloWorld(name : "Charlie").start(); actor.send('hello') GPars Actors Hello World: Actor Usage Groovy Actors
  • 47. Actors in the Real World
  • 48. Ericson AXD 301 switch millions of calls per ,99.9999999 percent uptime Facebook chat application 70 million concurrent users RabbitMQ high-performance AMQP, 400,000 messages per second. Apache CouchDB distributed, fault-tolerant document-oriented database Ejabberd XMPP server – jabber.org Erlang Actors in the Real World Actors in the Real World
  • 49. Easier to reason about Higher abstraction level Easier to avoid Race conditions Deadlocks Starvation Live locks Distributed computing Actor Benefits Actors in the Real World
  • 50. Actors don’t work well when Shared state is needed F.e. bank account Need to achieve global consensus Synchronous behavior is required It is not always trivial to break the problem into smaller problems Problems with Actors Actors in the Real World
  • 52. 1995 Nir Shavit and Dan Touitou Memory as a transactional data set Alternative to lock based synchronization Similar to database transactions Optimistic Approach a thread completes modifications to shared memory without regard for what other threads might be doing Software Transactional Memory More Concurrency Models
  • 53. Java STM framework by Guy Korland (TAU, GigaSpaces) @Atomic methods Field based access More scalable than Object bases. More efficient than word based. No reserved words No need for new compilers (Existing IDEs can be used) Using bytecode instrumentation (ASM) Deuce More 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 Example More 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 Hood More Concurrency Models
  • 56. Pros Performance gains on multi processor machines Simple approach to concurrency No deadlocks or livelocks Cons Transactions cannot perform any operation that cannot be undone STM Pros and Cons More Concurrency Models
  • 58. The free lunch is over Applications must be built for concurrency Shared state concurrency is hard Alternative concurrency models Message passing concurrency Shared Transactional Memory Summary Summary
  • 59. The free lunch is over State: You're Doing It Wrong Edward A. Lee, The Problem with Threads (PDF) Alex Miller – Actor Concurrency Deuce STM Resources Summary