SlideShare a Scribd company logo
1 of 54
Download to read offline
GPars workshop
Václav Pech
http://jroller.com/vaclav
Russel Winder
http://www.russel.org.uk
Agenda
● Threads, thread pools, tasks
● Agents
● Fork/Join
● Parallel collections
● Dataflow
● Actors
http://gpars.org/GPars_workshop.zip
We’re all in the parallel computing business!
Multithreaded programs today work mostly by accident!
Map/ReduceMap/Reduce
Fork/JoinFork/Join
ActorsActors
STMSTM
DataflowDataflow
AgentAgent
Can we do better?
Part 1
Thread management
Asynchronous invocation
Future f = threadPool.submit(calculation);
…
System.out.println(“Result: “ + f.get());
Async the Groovy way
def group = new NonDaemonPGroup(10)
group.task {
calculation.process()
}
Part 2
Agents
Shared Mutable State
Misused most of the time
When really needed, use
 Agents
 Software Transactional Memory
 Locks
Agent inside
Double IncrementAdd 25
Message Queue
36 thread
Agent List
def jugMembers = new Agent(['Me']) //add Me
task {
jugMembers.send {it.add 'Joe'} //add Joe
}
task {
jugMembers << {it.add 'Dave'} //add Dave
jugMembers << {it.add 'Alice'} //add Alice
}
...
println jugMembers.val
Part 3
Fork/Join
Thread Pool
Tasks
Worker threads
Queue
Thread Pool
Contention!
Fork/Join Thread Pool
Fork/Join Thread Pool
Work stealing
Fork/Join
 Solve hierarchical
problems
 Divide and conquer
 Merge sort, Quick sort
 Tree traversal
 File scan / search
 …
[a, b, c, d, e, f, g, h]
[a, b, c, d] [e, f, g, h]
[a, b] [c, d] [e, f] [g, h]
Fork/Join (GPars)
runForkJoin(new File(“./src”)) {currentDir ->
long count = 0;
currentDir.eachFile {
if (it.isDirectory()) {
forkOffChild it
} else {
count++
}
}
return count + childrenResults.sum(0)
}
Waits for children
without blocking the
thread!
Part 4
Parallel collections
Parallel collections
images.eachParallel {it.process()}
documents.sumParallel()
candidates.maxParallel {it.salary}.marry()
Parallel collections
registrations = submissions
.collectParallel { form -> form.process()}
.findAllParallel { it.valid }
registrations = submissions.parallel
.map { form -> form.process()}
.filter { it.valid }.collection
GPU
Java watch list:
https://github.com/pcpratts/rootbeer1/
http://openjdk.java.net/projects/sumatra/
Part 5
Dataflow
Composing async functions
int hash1 = hash(download('http://www.gpars.org'))
int hash2 = hash(loadFile('/gpars/website/index.html'))
boolean result = compare(hash1, hash2)
println result
Composing async functions
@AsyncFun hash = oldHash
@AsyncFun compare = oldCompare
@AsyncFun download = oldDownload
@AsyncFun loadFile = oldLoadFile
def hash1 = hash(download('http://www.gpars.org'))
def hash2 = hash(loadFile('/gpars/website/index.html'))
def result = compare(hash1, hash2)
println result.get()
Composing async functions
@AsyncFun hash = oldHash
@AsyncFun(blocking = true) compare = oldCompare
@AsyncFun download = oldDownload
@AsyncFun loadFile = oldLoadFile
def hash1 = hash(download('http://www.gpars.org'))
def hash2 = hash(loadFile('/gpars/website/index.html'))
boolean result = compare(hash1, hash2)
println result
int hash(String text) {…}
Promise<int> hash(Promise<String> | String text)
int hash(String text) {…}
Promise<int> hash(Promise<String> | String text)
compare(
hash( download() ),
hash( loadFile() )
)
int hash(String text) {…}
Promise<int> hash(Promise<String> | String text) {
1.Return a Promise for the result
2.Wait (non-blocking) for the text param
3.Call the original hash()
4.Bind the result
}
Composing async functions
Combine functions as usual
Parallelism is detected automatically
Composing async functions
@AsyncFun hash = oldHash
@AsyncFun compare = oldCompare
@AsyncFun download = oldDownload
@AsyncFun loadFile = oldLoadFile
def hash1 = hash(download('http://www.gpars.org'))
def hash2 = hash(loadFile('/gpars/website/index.html'))
def result = compare(hash1, hash2)
println result.get()
Promise chaining
@AsyncFun download = oldDownload
@AsyncFun loadFile = oldLoadFile
def h1 = download('http://www.gpars.org') then hash
def h2 = loadFile('/gpars/website/index.html') then hash
whenAllBound([h1, h2], compare) then {println it}
Promise chaining
@AsyncFun download = oldDownload
@AsyncFun loadFile = oldLoadFile
whenAllBound ([
download('http://www.gpars.org') >> hash,
loadFile('/gpars/website/index.html') >> hash
], compare) >> {println it}
Dataflow Concurrency
 No race-conditions
 No live-locks
 Deterministic deadlocks
Completely deterministic programs
BEAUTIFUL code
(Jonas Bonér)
Dataflow Variables / Promises
main task2 task3
x
yz
task1
Dataflow Variables / Promises
task2
x
task1
Promises to exchange data
task { z << x.val + y.val }
task { x << 10 }
task {
println ”I am task 3”
y << 5
}
assert 15 == z.val
Dataflow Variables / Promises
task2
x
task1
Dataflow Channels
task2
x|y|z
task1
Synchronous Channels
task2
x|y|z
task1
operator(inputs: [headers, bodies, footers],
outputs: [articles, summaries])
{header, body, footer ->
def article = buildArticle(header, body, footer)
bindOutput(0, article)
bindOutput(1, buildSummary(article))
} *
+
<>
Dataflow Operators
Url resolverUrl resolver
Downloader
Groovy scanner Scala scanner
Url resolverUrl resolver
Reporter
Speculator
Evaluator
Splitter
Confirm
Cache
updates
Approvals
Dataflow Operators
Part 6
Actors
Actors
Processes with a mail-box
Share no data
Communicate by sending messages
Use a thread-pool
Actors
 Isolated
 Communicating
Immutable messages
 Active
Pooled shared threads
 Activities
Create a new actor
Send a message
Receive a message
Actor
Actor
Actor
Actor
Actor
Actor
Actor
T
T
T
Thread pool
Actors use
Gate
Keeper
Form
HTTP
Finger
Prints
Address
Check
Email
Check
Process
Fraud
Detect
Response
SOAP
SMTP
Sending messages
buddy.send 10.eur
buddy << new Book(title:’Groovy Recipes’,
author:’Scott Davis’)
def canChat = buddy.sendAndWait ‘Got time?’
buddy.sendAndContinue ‘Need money!’, {cash->
pocket.add cash
}
Stateless Actors (pure Java)
class MyActor extends DynamicDispatchActor {
Account account = ...
public void onMessage(String msg) {
String encripted = encrypt(msg);
reply(encripted);
}
public void onMessage(Integer number) {
reply(2 * number);
}
public void onMessage(Money cash) {
System.out.println("Received a donation " + cash);
account.deposit(cash);
}
}
Stateful Actors
class MyActor extends DefaultActor {
void act() {
def buddy = new YourActor()
buddy << ‘Hi man, how’re things?’
def response = receive()
}
}
Implicit State in Actors
val me = actor {
react {msg1 ->
switch (msg1) {
case Work: reply “I don't work so early” ; stop();
case Breakfast:
msg1.eat()
react {msg2 →
switch (msg2) {
case Work: reply “OK, time to work”; msg2.do()
case Lunch: ...
} } } }
Continuation Style
loop {
…
react {
…
react {/*schedule the block; throw CONTINUE*/
…
}
//Never reached
}
//Never reached
}
//Never reached
Active Objects
@ActiveObject
class MyCounter {
private int counter = 0
@ActiveMethod
def incrementBy(int value) {
println "Received an integer: $value"
this.counter += value
}
}
'coz concurrency is Groovy

More Related Content

What's hot

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020InfluxData
 
C# console programms
C# console programmsC# console programms
C# console programmsYasir Khan
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Flink Forward
 
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 objectsMikhail Girkin
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programsMukesh Tekwani
 
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 Seiya Mizuno
 
Python in the database
Python in the databasePython in the database
Python in the databasepybcn
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiInfluxData
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)Takayuki Goto
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJSMattia Occhiuto
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicBadoo Development
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 

What's hot (20)

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020
 
C# console programms
C# console programmsC# console programms
C# console programms
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School Vasia Kalavri – Training: Gelly School
Vasia Kalavri – Training: Gelly School
 
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
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programs
 
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
 
Python in the database
Python in the databasePython in the database
Python in the database
 
Lab 1
Lab 1Lab 1
Lab 1
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 

Similar to Gpars workshop

GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...dantleech
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internalsKostas Tzoumas
 
Gpars concepts explained
Gpars concepts explainedGpars concepts explained
Gpars concepts explainedVaclav Pech
 
Akka with Scala
Akka with ScalaAkka with Scala
Akka with ScalaOto Brglez
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformMartin Zapletal
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 

Similar to Gpars workshop (20)

GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
G pars
G parsG pars
G pars
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internals
 
Flink internals web
Flink internals web Flink internals web
Flink internals web
 
Gpars concepts explained
Gpars concepts explainedGpars concepts explained
Gpars concepts explained
 
Akka with Scala
Akka with ScalaAkka with Scala
Akka with Scala
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive Platform
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 

More from Vaclav Pech

Domain Specific Language with pleasure
Domain Specific Language with pleasureDomain Specific Language with pleasure
Domain Specific Language with pleasureVaclav Pech
 
Concepts of JetBrains MPS
Concepts of JetBrains MPSConcepts of JetBrains MPS
Concepts of JetBrains MPSVaclav Pech
 
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 workbenchesVaclav Pech
 
Get 'em before they get You
Get 'em before they get YouGet 'em before they get You
Get 'em before they get YouVaclav Pech
 
Groovy in IntelliJ IDEA
Groovy in IntelliJ IDEAGroovy in IntelliJ IDEA
Groovy in IntelliJ IDEAVaclav Pech
 

More from Vaclav Pech (7)

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
 
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
 

Gpars workshop