SlideShare a Scribd company logo
1 of 48
Download to read offline
GPars
'coz concurrency is Groovy
Václav Pech
Asynchronous calculations
Fork/Join
Parallel collections
Actors
Agents, Stm
Dataflow
CSP
Why this talk?
Structure
Parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Structure
Parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Parallelism
Task parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Asynchronous invocation
Future f = threadPool.submit(calculation);
…
System.out.println(“Result: “ + f.get());
Async the Groovy way
task {
calculation.process()
}
Async the Groovy way
def group = new NonDaemonPGroup(10)
group.task {
calculation.process()
}
group.task {->…}
group.task new Runnable() {…}
group.task new Callable<V>() {...}
Async the Groovy way
Independent tasks
def group = new NonDaemonPGroup(10)
submissions.each {form →
group.task {
form.process()
}
}
Dependent tasks
Parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
State sharing
Parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
State sharing
List registrations = []
submissions.each {form →
group.task {
if (form.process().valid) {
registrations << form
}
}
}
State sharing
List registrations = []
submissions.each {form →
group.task {
if (form.process().valid) {
registrations << form
}
}
}
Needs protection
Agent
 Lock Shared Mutable State in a Safe
Alter
the
State
Alter
the
State
Agent inside
Double IncrementAdd 25
Message Queue
36 thread
Sharing through agents
Agent registrations = group.agent( [] )
submissions.each {form →
group.task {
if (form.process().valid) {
registrations.send {it << form}
}
}
}
Random task dependency
Parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Dataflow Concurrency
No race-conditions
No live-locks
Deterministic deadlocks
Dataflow Variables / Promises
main task2 task3
x
yz
task1
Dataflow Variables / Promises
task2
x
task1
Dataflow Variables / Promises
main task2 task3
x
yz
task1
Chaining promises
def h1 = download('url') then {text → text.trim()} then hash
Error handling
url.then(download)
.then(calculateHash)
.then(formatResult)
.then(printResult, printError)
.then(sendNotificationEmail);
List registrations = []
List<Promise> forms=submissions.collect {form →
group.task {
if (form.process().valid) return form
}
}
forms.each{registrations << it.get()}
Pass results around
Dataflow Variables / Promises
task2
x
task1
Dataflow Channels
task2
x|y|z
task1
Synchronous Channels
task2
x|y|z
task1
Tasks with progress indication
List<Promise> forms=submissions.collect {form →
group.task {
def result = form.process()
progressQueue << 1
if (result.valid) {
return form
}
}
}
Channel Selection
Select alt = group.select(validForms, invalidForms)
SelectResult selectResult = alt.select() //alt.prioritySelect()
switch (selectResult.index) {
case 0: registrations << selectResult.value; break
case 1: ...
}
Parallelism
Data parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Parallelism
Data parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Geometric decomposition
images.eachParallel {it.process()}
documents.sumParallel()
candidates.maxParallel {it.salary}.marry()
Geometric decomposition
registrations = submissions
.collectParallel { form -> form.process()}
.findAllParallel { it.valid }
registrations = submissions.parallel
.map { form -> form.process()}
.filter { it.valid }.collection
Frequent confusion
Improper use 1
def accumulator = 0
myCollection.eachParallel {
accumulator += calculate(it)
}
Improper use 2
new File("/file.txt").withReader{reader ->
reader.eachParallel {
def r1 = step1(r)
def r2 = step2(r1)
def r3 = step3(r2)
}
}
Unroll iteration
def pipeline = data | step1 | step2 | step3
new File("/file.txt").withReader{reader ->
reader.each {
data << it
}
}
Unroll iteration
Parallelism
Streamed data
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Pipeline DSL
def toProcess = new DataflowQueue()
def validated = new DataflowQueue()
toProcess | {form -> process(form)} |
{processedForm -> validate(processedForm)} | validated
submissions.each {toProcess << it}
Url resolverUrl resolverUrl resolverprocess
validate
inProcess
validated
Url resolverUrl resolver
Downloader
Groovy scanner Scala scanner
Url resolverUrl resolver
Reporter
Speculator
Evaluator
Splitter
Confirm
Cache
updates
Approvals
Dataflow Operators
operator(inputs: [headers, bodies, footers],
outputs: [articles, summaries])
{header, body, footer ->
def article = buildArticle(header, body, footer)
bindOutput(0, article)
bindOutput(1, buildSummary(article))
}
Conclusion
Parallelism
Task Data
Random
Independent Dependent
Hierarchical
Geometrical
Streamed
Event-driven
Functional
Hierarchical
Shared state
Summary
Parallelism is not hard, multi-threading is
Jon Kerridge, Napier University
Questions?
Find more at:
http://gpars.codehaus.org
http://www.jroller.com/vaclav
http://twitter.com/vaclav_pech

More Related Content

What's hot

Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
Dmitry Buzdin
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
Ted Leung
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 

What's hot (20)

Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
C# console programms
C# console programmsC# console programms
C# console programms
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
 
Lab 1
Lab 1Lab 1
Lab 1
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams Connect S3 with Kafka using Akka Streams
Connect S3 with Kafka using Akka Streams
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programs
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
Using akka streams to access s3 objects
Using akka streams to access s3 objectsUsing akka streams to access s3 objects
Using akka streams to access s3 objects
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Python in the database
Python in the databasePython in the database
Python in the database
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 

Similar to GPars howto - when to use which concurrency abstraction

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 

Similar to GPars howto - when to use which concurrency abstraction (20)

Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Transition graph using free monads and existentials
Transition graph using free monads and existentialsTransition graph using free monads and existentials
Transition graph using free monads and existentials
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
Functional Programming with Javascript
Functional Programming with JavascriptFunctional Programming with Javascript
Functional Programming with Javascript
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
ppt - Deep Learning From Scratch.pdf
ppt - Deep Learning From Scratch.pdfppt - Deep Learning From Scratch.pdf
ppt - Deep Learning From Scratch.pdf
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at... Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
 
React 101
React 101React 101
React 101
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 

More from Vaclav Pech (8)

Domain Specific Language with pleasure
Domain Specific Language with pleasureDomain Specific Language with pleasure
Domain Specific Language with pleasure
 
Concepts of JetBrains MPS
Concepts of JetBrains MPSConcepts of JetBrains MPS
Concepts of JetBrains MPS
 
Advanced IDE functionality in modern language workbenches
Advanced IDE functionality in modern language workbenchesAdvanced IDE functionality in modern language workbenches
Advanced IDE functionality in modern language workbenches
 
Get 'em before they get You
Get 'em before they get YouGet 'em before they get You
Get 'em before they get You
 
Gpars concepts explained
Gpars concepts explainedGpars concepts explained
Gpars concepts explained
 
Groovy in IntelliJ IDEA
Groovy in IntelliJ IDEAGroovy in IntelliJ IDEA
Groovy in IntelliJ IDEA
 
Groovy Intro
Groovy IntroGroovy Intro
Groovy Intro
 
Team City
Team CityTeam City
Team City
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

GPars howto - when to use which concurrency abstraction