SlideShare a Scribd company logo
1 of 46
GPars
Code Camp - June 2016
Presented by - Vishal and Nakul
Agenda
Problems
GPars Introduction
Getting started with GPars
Data Parallelism and concepts
Actors
Agents
Dataflow
Conclusion
Single Core vs Multi Core
GPars History
2008: In October 2008, Vaclav Pech started a pet open-source project called
GParallelizer with the intention to build several easy-to-use Groovy-based
DSLs.
2009: In September 2009, Dierk Koenig, Alex Tkachman, Russel Winder and Paul
King joined the team, when the project moved to Codehaus under a new
name — GPars.
The team made their first release under the new project name in December
2009 when GPars 0.9 came out with a fancy User Guide.
Bundeled in Groovy since 1.8
Introduction
GPars (Groovy Parallel Systems) is an open-source concurrency and
parallelism library for Java and Groovy that gives you a number of high-level
abstractions for writing concurrent and parallel code in Groovy (map/reduce,
fork/join, asynchronous closures, actors, agents, dataflow concurrency and
other concepts), which can make your Java and Groovy code concurrent
and/or parallel with little effort.
With GPars your Java and/or Groovy code can easily utilize all the available
processors on the target system.
Introduction Continued..
Many high-level concepts, such as actors and dataflow have been around for
quite some time: parallel computers have been in use, at least in data centres
if not on the desktop, long before multi-core chips hit the hardware
mainstream.
This is what GPars enables for the Groovy and Java languages, allowing
Groovy and Java programmers to use higher-level abstractions and therefore
make developing concurrent and parallel software easier and less error
prone.
Concepts
1. Map Reduce
2. Data parallelism
3. Asynchronous Processing
4. Parallel Collections
5. Actors
Map Reduce Concept
Map Reduce Example
Getting started with GPars
Dependency for Gradle
"org.codehaus.gpars:gpars:1.2.1"
Dependency for Maven
<dependency>
<groupId>org.codehaus.gpars</groupId>
<artifactId>gpars</artifactId>
<version>1.2.0</version>
</dependency>
Groovy Sequential Collection
GPars Parallel Collection
Data Parallelism
Dealing with data frequently involves manipulating collections
Lists, arrays, sets, maps, iterators, strings etc. can be viewed as collections
of items
Common pattern to process such collections is to take elements sequentially,
one-by-one, and make an action for each of the items in row.
E.g min() function – Iterates over the collection sequentially to find the
minimum value
Data Parallelism - Parallel Collection
The GParsPool class enables a ParallelArray-based (from JSR-166y)
concurrency DSL for collections and objects.
GParsPool.withPool(){ .. }
GParsPool.withPool(){ ForkJoinPool pool ->.. }
GParsPool.withPool(10){ .. }
GParsPool.withExistingPool(ForkJoinPool pool){ .. }
Data Parallelism - Parallel Collection
Some of the methods supported are -
eachParallel() , collectParallel(),
findAllParallel() , findAnyParallel(),
groupByParallel(), minParallel(),
maxParallel(), sumParallel(),
countParallel()
Test URL - http://localhost:8080/gpars/parallelData
Data Parallelism - Parallel Enhancer
ParallelEnhancer makes a collection to be executed parallel without using
GPars.withPool{}
Example -
def animals = ['dog' , 'ant' , 'cat' , 'whale']
ParallelEnhancer.enhanceInstance(animals)
println(animals.everyParallel{it.contains("a")} ? 'All animals contain a' :
'Some animals can live without a')
Data Parallelism - Map/Filter/Reduce
Can be used for the same purpose as the xxxParallel() family methods and has
very similar semantics.
Can perform considerably faster if you need to chain multiple methods to
process a single collection in multiple steps.
Ex- def myNumbers = (1..1000).parallel.filter{it % 2 == 0}.map{Math.sqrt
it}.collection
Internally they build ParallelArray, perform required operation concurrently
and destroy ParallelArray before returning
Data Parallelism - Map/Filter/Reduce Methods
o map()
o reduce()
o filter()
o size()
o sum()
o min()
Data Parallelism - Asynchronous Invocation
The following methods are added to closures inside the
GPars(Executors)Pool.withPool() blocks:
o async() - Creates an asynchronous variant of the supplied closure,
which when invoked returns a future for the potential return value
o callAsync() - Calls a closure in a separate thread supplying the given
arguments, returning a future for the potential return value,
MemoizeThe memoize function enables caching of function's return values. Repeated calls to
the memoized function with the same argument values will, instead of invoking the
calculation encoded in the original function.
gmemoize()
gmemoizeAtMost()
gmemoizeAtLeast()
gmemoizeBetween
Actors Introduction
Allow for a message passing-based concurrency model
Every actor has a mailbox for messages and messages are processed one by one
Programs are collections of independent active objects that exchange
messages and have no mutable shared state.
Always guarantee that at most one thread processes the actor's body.
Actors in action
Helps to avoid deadlock, live-lock and starvation
A great number of actors can share a relatively small thread pool
An actor with no work doesn't consume threads.
No shared mutable state.
Runs in daemon threads.
Actors
Actors commands
Messages can be sent to actors using
1. send() method
2. << operator
3. Implicit call() method
Actor- Sending Messages
def passiveActor = Actors.actor{
loop {
react { msg -> println "Received: $msg"; }
}
}
passiveActor.send 'Message 1'
passiveActor << 'Message 2'
passiveActor 'Message 3'
Actor - Sending Messages
1. sendAndWait() //Blocks the caller until a reply from the actor is available.
2. sendAndPromise()
3. sendAndContinue()
Actor- Receiving Messages
react{ }
Closure within Actor's code is responsible to consume message from actor's
inbox
react { message ->
//consume message...
}
Wait's if there is no message to be processed immediately ??
Supplied closure is not invoked directly. It is scheduled for processing by any
thread in the thread pool once a message is available
Demo - Actors
Agents
● Inspired by Agents in Clojure
● Used when shared mutable state is required e.g Shopping Cart
● Is a thread-safe non-blocking shared mutable state wrapper
● Hides data and protects from direct access
● Accepts messages and process them asynchronously
Agents in action
● Messages are commands(functions) and executed inside Agent
● Agent guarantees execution of a single function at a time
● After reception, received function is run against the internal state of
Agent and return value is new internal state of Agent
● The mutable values are not directly accessible from outside
Agents
Requests have to be sent to Agent
Agent guarantees to process the requests seqentially on behaf of callers
Wraps a reference to mutable state held inside a single field
Messages can be sent via
'<<' operator
send() method
Implicit call() method
Agents
Submitted commands obtain the agent's state as a parameter.
Can call any methods on the agent's state.
Replacing the state object with a new one is also possible using the
updateValue() method.
The val property waits until all preceding commands are consumed.
Agents
The valAsync() does not block caller.
The instantVal returns immediate snapshot of agent state.
All Agent instances share a default daemon thread pool.
Setting the threadPool property of an Agent instance will allow it to use a
different thread pool.
Demo - Agents
Dataflow
● Operations in Dataflow programs consists of “Black Boxes”
● Inputs and Outputs are always explicitly defined.
● They run as soon as all of their inputs become valid.
● Dataflow program is more like series of workers in assembly line
They are inherently parallel.
Dataflow
Dataflow is a channel to safely and reliably transfer data from producers to
their consumers
Value is set using '<<' operator
A task blocks until value has been set by another task
DF Variable can only be set only one in its lifetime
Don't have to bother with ordering and synchronizing the tasks or threads
Dataflow - Sample Program
def x = new DataflowVariable()
def y = new DataflowVariable()
def z = new DataflowVariable()
task { z << x.val + y.val }
task{ x << 10 }
task{ y << 5 }
println "Result : $z.val"
Dataflow Benefits
No race-conditions
No live-locks
Deterministic deadlocks
Completely deterministic programs
Beautiful Code
Demo - Dataflow
Tips
1. When chaining parallel method calls you might consider using the
map/reduce API instead or resort to using the ParallelArray API directly, to
avoid the Parallel Array creation overhead.
2. The GParsConfig.shutdown() method can be used in managed
environments to properly shutdown all asynchronously run timers and
free the memory from all thread-local variables.
3. GPars Agents are even a bit faster in processing messages than actors
4. In many scenarios changing the pool size from the default value may give
you performance benefits. Especially if your tasks perform IO operations,
like file or database access, networking and such, increasing the number
Conclusion
1. You're certainly ready to build fast, robust and reliable concurrent
applications.
2. You've seen that there are many concepts you can choose from and each
has its own areas of applicability.
3. The ability to pick the right concept to apply to a given problem and
combine it with the rest of the system is key to being a successful
developer.
References
1. GPars User Guide
2. Groovy in Action, Second Edition - Manning Publication
3. Concurrency with GPars - Dr. Paul King
4. GPars - Gagan Agrawal
Github Project
Please refer below for live implementation:-
https://github.com/NexThoughts/Grails-Gpars-Example-Demo
Good use cases
Parallelizer: https://github.com/GPars/GPars/blob/master/src/test/groovy/groovyx/gpars/ParallelizerTest.groovy
https://github.com/GPars/GPars/blob/master/src/test/groovy/groovyx/gpars/samples/collections/DemoMapReduce.g
roovy
https://github.com/GPars/GPars/blob/master/src/test/groovy/groovyx/gpars/MapReduceTest.groovy
Questions ?
Thank You

More Related Content

What's hot

Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails FrameworkPT.JUG
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptDhruvin Shah
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Devang Garach
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJSSumanth krishna
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React NativeSoftware Guru
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 

What's hot (20)

Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails Framework
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJS
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Servlet11
Servlet11Servlet11
Servlet11
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 

Viewers also liked (20)

Grails internationalization-160524154831
Grails internationalization-160524154831Grails internationalization-160524154831
Grails internationalization-160524154831
 
Bootcamp linux commands
Bootcamp linux commandsBootcamp linux commands
Bootcamp linux commands
 
Twilio
TwilioTwilio
Twilio
 
Gorm
GormGorm
Gorm
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Grails services
Grails servicesGrails services
Grails services
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
Groovy DSL
Groovy DSLGroovy DSL
Groovy DSL
 
Command objects
Command objectsCommand objects
Command objects
 
Grails domain classes
Grails domain classesGrails domain classes
Grails domain classes
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Apache tika
Apache tikaApache tika
Apache tika
 
Advanced criteria queries
Advanced criteria queriesAdvanced criteria queries
Advanced criteria queries
 
Elastic search
Elastic searchElastic search
Elastic search
 

Similar to G pars

GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)Gagan Agrawal
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Paddy Lock
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
Stateful streaming data pipelines
Stateful streaming data pipelinesStateful streaming data pipelines
Stateful streaming data pipelinesTimothy Farkas
 
Airflow tutorials hands_on
Airflow tutorials hands_onAirflow tutorials hands_on
Airflow tutorials hands_onpko89403
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSuzquiano
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...Codemotion
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootVMware Tanzu
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practiceDocker, Inc.
 
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
Strata Singapore: GearpumpReal time DAG-Processing with Akka at ScaleStrata Singapore: GearpumpReal time DAG-Processing with Akka at Scale
Strata Singapore: Gearpump Real time DAG-Processing with Akka at ScaleSean Zhong
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptJohn Stevenson
 

Similar to G pars (20)

GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners Clojure Fundamentals Course For Beginners
Clojure Fundamentals Course For Beginners
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 
Tech talk
Tech talkTech talk
Tech talk
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Stateful streaming data pipelines
Stateful streaming data pipelinesStateful streaming data pipelines
Stateful streaming data pipelines
 
Airflow tutorials hands_on
Airflow tutorials hands_onAirflow tutorials hands_on
Airflow tutorials hands_on
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practice
 
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
Strata Singapore: GearpumpReal time DAG-Processing with Akka at ScaleStrata Singapore: GearpumpReal time DAG-Processing with Akka at Scale
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Recently uploaded

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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 

Recently uploaded (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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
 

G pars

  • 1. GPars Code Camp - June 2016 Presented by - Vishal and Nakul
  • 2. Agenda Problems GPars Introduction Getting started with GPars Data Parallelism and concepts Actors Agents Dataflow Conclusion
  • 3. Single Core vs Multi Core
  • 4. GPars History 2008: In October 2008, Vaclav Pech started a pet open-source project called GParallelizer with the intention to build several easy-to-use Groovy-based DSLs. 2009: In September 2009, Dierk Koenig, Alex Tkachman, Russel Winder and Paul King joined the team, when the project moved to Codehaus under a new name — GPars. The team made their first release under the new project name in December 2009 when GPars 0.9 came out with a fancy User Guide. Bundeled in Groovy since 1.8
  • 5. Introduction GPars (Groovy Parallel Systems) is an open-source concurrency and parallelism library for Java and Groovy that gives you a number of high-level abstractions for writing concurrent and parallel code in Groovy (map/reduce, fork/join, asynchronous closures, actors, agents, dataflow concurrency and other concepts), which can make your Java and Groovy code concurrent and/or parallel with little effort. With GPars your Java and/or Groovy code can easily utilize all the available processors on the target system.
  • 6. Introduction Continued.. Many high-level concepts, such as actors and dataflow have been around for quite some time: parallel computers have been in use, at least in data centres if not on the desktop, long before multi-core chips hit the hardware mainstream. This is what GPars enables for the Groovy and Java languages, allowing Groovy and Java programmers to use higher-level abstractions and therefore make developing concurrent and parallel software easier and less error prone.
  • 7. Concepts 1. Map Reduce 2. Data parallelism 3. Asynchronous Processing 4. Parallel Collections 5. Actors
  • 10. Getting started with GPars Dependency for Gradle "org.codehaus.gpars:gpars:1.2.1" Dependency for Maven <dependency> <groupId>org.codehaus.gpars</groupId> <artifactId>gpars</artifactId> <version>1.2.0</version> </dependency>
  • 13. Data Parallelism Dealing with data frequently involves manipulating collections Lists, arrays, sets, maps, iterators, strings etc. can be viewed as collections of items Common pattern to process such collections is to take elements sequentially, one-by-one, and make an action for each of the items in row. E.g min() function – Iterates over the collection sequentially to find the minimum value
  • 14. Data Parallelism - Parallel Collection The GParsPool class enables a ParallelArray-based (from JSR-166y) concurrency DSL for collections and objects. GParsPool.withPool(){ .. } GParsPool.withPool(){ ForkJoinPool pool ->.. } GParsPool.withPool(10){ .. } GParsPool.withExistingPool(ForkJoinPool pool){ .. }
  • 15. Data Parallelism - Parallel Collection Some of the methods supported are - eachParallel() , collectParallel(), findAllParallel() , findAnyParallel(), groupByParallel(), minParallel(), maxParallel(), sumParallel(), countParallel() Test URL - http://localhost:8080/gpars/parallelData
  • 16. Data Parallelism - Parallel Enhancer ParallelEnhancer makes a collection to be executed parallel without using GPars.withPool{} Example - def animals = ['dog' , 'ant' , 'cat' , 'whale'] ParallelEnhancer.enhanceInstance(animals) println(animals.everyParallel{it.contains("a")} ? 'All animals contain a' : 'Some animals can live without a')
  • 17. Data Parallelism - Map/Filter/Reduce Can be used for the same purpose as the xxxParallel() family methods and has very similar semantics. Can perform considerably faster if you need to chain multiple methods to process a single collection in multiple steps. Ex- def myNumbers = (1..1000).parallel.filter{it % 2 == 0}.map{Math.sqrt it}.collection Internally they build ParallelArray, perform required operation concurrently and destroy ParallelArray before returning
  • 18. Data Parallelism - Map/Filter/Reduce Methods o map() o reduce() o filter() o size() o sum() o min()
  • 19. Data Parallelism - Asynchronous Invocation The following methods are added to closures inside the GPars(Executors)Pool.withPool() blocks: o async() - Creates an asynchronous variant of the supplied closure, which when invoked returns a future for the potential return value o callAsync() - Calls a closure in a separate thread supplying the given arguments, returning a future for the potential return value,
  • 20. MemoizeThe memoize function enables caching of function's return values. Repeated calls to the memoized function with the same argument values will, instead of invoking the calculation encoded in the original function. gmemoize() gmemoizeAtMost() gmemoizeAtLeast() gmemoizeBetween
  • 21. Actors Introduction Allow for a message passing-based concurrency model Every actor has a mailbox for messages and messages are processed one by one Programs are collections of independent active objects that exchange messages and have no mutable shared state. Always guarantee that at most one thread processes the actor's body.
  • 22. Actors in action Helps to avoid deadlock, live-lock and starvation A great number of actors can share a relatively small thread pool An actor with no work doesn't consume threads. No shared mutable state. Runs in daemon threads.
  • 24. Actors commands Messages can be sent to actors using 1. send() method 2. << operator 3. Implicit call() method
  • 25. Actor- Sending Messages def passiveActor = Actors.actor{ loop { react { msg -> println "Received: $msg"; } } } passiveActor.send 'Message 1' passiveActor << 'Message 2' passiveActor 'Message 3'
  • 26. Actor - Sending Messages 1. sendAndWait() //Blocks the caller until a reply from the actor is available. 2. sendAndPromise() 3. sendAndContinue()
  • 27. Actor- Receiving Messages react{ } Closure within Actor's code is responsible to consume message from actor's inbox react { message -> //consume message... } Wait's if there is no message to be processed immediately ?? Supplied closure is not invoked directly. It is scheduled for processing by any thread in the thread pool once a message is available
  • 29. Agents ● Inspired by Agents in Clojure ● Used when shared mutable state is required e.g Shopping Cart ● Is a thread-safe non-blocking shared mutable state wrapper ● Hides data and protects from direct access ● Accepts messages and process them asynchronously
  • 30. Agents in action ● Messages are commands(functions) and executed inside Agent ● Agent guarantees execution of a single function at a time ● After reception, received function is run against the internal state of Agent and return value is new internal state of Agent ● The mutable values are not directly accessible from outside
  • 31. Agents Requests have to be sent to Agent Agent guarantees to process the requests seqentially on behaf of callers Wraps a reference to mutable state held inside a single field Messages can be sent via '<<' operator send() method Implicit call() method
  • 32. Agents Submitted commands obtain the agent's state as a parameter. Can call any methods on the agent's state. Replacing the state object with a new one is also possible using the updateValue() method. The val property waits until all preceding commands are consumed.
  • 33. Agents The valAsync() does not block caller. The instantVal returns immediate snapshot of agent state. All Agent instances share a default daemon thread pool. Setting the threadPool property of an Agent instance will allow it to use a different thread pool.
  • 35. Dataflow ● Operations in Dataflow programs consists of “Black Boxes” ● Inputs and Outputs are always explicitly defined. ● They run as soon as all of their inputs become valid. ● Dataflow program is more like series of workers in assembly line They are inherently parallel.
  • 36. Dataflow Dataflow is a channel to safely and reliably transfer data from producers to their consumers Value is set using '<<' operator A task blocks until value has been set by another task DF Variable can only be set only one in its lifetime Don't have to bother with ordering and synchronizing the tasks or threads
  • 37. Dataflow - Sample Program def x = new DataflowVariable() def y = new DataflowVariable() def z = new DataflowVariable() task { z << x.val + y.val } task{ x << 10 } task{ y << 5 } println "Result : $z.val"
  • 38. Dataflow Benefits No race-conditions No live-locks Deterministic deadlocks Completely deterministic programs Beautiful Code
  • 40. Tips 1. When chaining parallel method calls you might consider using the map/reduce API instead or resort to using the ParallelArray API directly, to avoid the Parallel Array creation overhead. 2. The GParsConfig.shutdown() method can be used in managed environments to properly shutdown all asynchronously run timers and free the memory from all thread-local variables. 3. GPars Agents are even a bit faster in processing messages than actors 4. In many scenarios changing the pool size from the default value may give you performance benefits. Especially if your tasks perform IO operations, like file or database access, networking and such, increasing the number
  • 41. Conclusion 1. You're certainly ready to build fast, robust and reliable concurrent applications. 2. You've seen that there are many concepts you can choose from and each has its own areas of applicability. 3. The ability to pick the right concept to apply to a given problem and combine it with the rest of the system is key to being a successful developer.
  • 42. References 1. GPars User Guide 2. Groovy in Action, Second Edition - Manning Publication 3. Concurrency with GPars - Dr. Paul King 4. GPars - Gagan Agrawal
  • 43. Github Project Please refer below for live implementation:- https://github.com/NexThoughts/Grails-Gpars-Example-Demo
  • 44. Good use cases Parallelizer: https://github.com/GPars/GPars/blob/master/src/test/groovy/groovyx/gpars/ParallelizerTest.groovy https://github.com/GPars/GPars/blob/master/src/test/groovy/groovyx/gpars/samples/collections/DemoMapReduce.g roovy https://github.com/GPars/GPars/blob/master/src/test/groovy/groovyx/gpars/MapReduceTest.groovy