SlideShare una empresa de Scribd logo
1 de 57
GPars(Groovy Parallel Systems)
Gagan Agrawal
Xebia
Agenda
What is Gpars?
Data Parallelism
Actors
Agents
Dataflow
Trend
Multi Core Processor
Problems with Java Concurrency Model
Synchronization
Dead-Locks
Live-Locks
Race Conditions
Starvation
GPars GOAL




    To fully utilize all available processors
What is GPars ?
An open-source concurrency and parallelism
library for Groovy and Java
Gives a number of high-level abstractions for
writing concurrent and parallel code
  Abstractions like..
Map-Reduce
Fork-Join
Asynchronous Closures
Actors
Agents
DataFlow
Data Parallelism
Data Parallelism
For low level data parallelism techniques

GParsPool – Relies on JSR-166y Fork/Join
Framework and offers greater functionality and
better performance.

GParsExecutorsPool – Uses old Java executors and
so is easy to setup in a managed or restricted
environment.
Data Parallelism – Parallel Collections
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
Parallel Collections with GParsPool
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){ .. }
Parallel Collections with GParsPool
 Some of the methods supported are -
eachParallel()
collectParallel()
findAllParallel()
findAnyParallel()
groupByParallel()
minParallel()
maxParallel()
sumParallel()
countParallel()
Parallel Collections with Meta-class enhancer

ParallelEnhancer



  def list = [1,2,3,4,5,6,7,8]
  ParallelEnhancer.enhanceInstance(list)
  println list.collectParallel{it * 2}
Parallel Collections with Meta-class enhancer

ParallelEnhancer


  def animals = ['dog','ant','cat','whale']
  ParallelEnhancer.enhanceInstance(animals)
  println(animals.anyParallel{it=='ant'} ? 'Found
  an ant' : 'No ants found')

  println(animals.everyParallel{it.contains("a")}
  ? 'All animals contain a' : 'Some animals can
  live without a')
Parallel Collections – Warning
Don't do this

  def thumbnails = []
  images.eachParallel{
     thumbnails << it.thumbnail
  }
Parallel Collections - Memoize

Enables caching of function's return values.

Repeated calls to the memoized function will
retrieve the result value from an internal
transparent cache.

Example
Data Parallelism – Map 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.

Example
Data Parallelism – Map Reduce
 How it is different from Parallel Collections
The xxxParallel() methods must return a legal collection of items.
Internally they build ParallelArray, perform required operation
concurrently and destroy ParallelArray before returning
Repeats same process for every xxxParallel() method call.
With Map-Reduce Parallel Array is created just once and same is
used in all chained method calls.
To get collection, retrieve "collection" property
Data Parallelism – Asynchronous Invocation

async() - Creates an asynchronous variant of the
supplied closure

  GParsPool.withPool{
      Closure longLastingCalculation = {calculate()}
      Closure fastCalculation =
              longLastingCalculation.async()
      Future result = fastCalculation()
      //do stuff while calculation performs...
      println result.get()
  }
Data Parallelism – Asynchronous Invocation
 callAsync() - Calls a closure in a separate thread
supplying the given arguments

  GParsPool.withPool{
     println ({it * 2}.call(3))
     println ({it * 2}.callAsync(3).get())
  }
Actors
Actors

Was originally inspired by the Actors library in
Scala
Allow for a message passing-based concurrency
model
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

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 - Types
 Stateless Actors
DynamicDispatchActor and Reactive Actor
Keep no track of what messages have arrived previously
 Stateful Actors
DefaultActor
Allows user to handle implicit state directly
After receiving a message the actor moves into a new state
with different ways to handle future messages
E.g Encrypted messages for decryption, only after it has
received the encryption keys
Stateful Actors
Can be created in one of two ways

By extending DefaultActor class

Static methods of Actors class
Actors - Usage
 Performs 3 specific operations

Send Messages

Receive Messages

Create new actors
Actors – Sending Messages
Messages can be sent to actors using

send() method

<< operator

Implicit call() method
Actors – Sending Messages

 def passiveActor = Actors.actor{
    loop {
       react { msg -> println "Received: $msg"; }
    }
 }

 passiveActor.send 'Message 1'
 passiveActor << 'Message 2'
 passiveActor 'Message 3'
Actors – Sending Messages


 sendAndWait()
Blocks the caller until a reply from the actor is
available.
Actors – Sending Messages
 def replyingActor = Actors.actor{
    loop {
       react { msg ->
           println "Received: $msg";
           reply "I've got $msg"
       }
    }
 }
 def reply1 = replyingActor.sendAndWait('Message 4')
 def reply2 = replyingActor.sendAndWait('Message 5',
 10, TimeUnit.SECONDS)
Actors – Sending Messages


 sendAndContinue()

  replyingActor.sendAndContinue("Message 6")
  {reply ->
     println "Got reply '${reply}'"
  }
  println "I can continue while replyingActor is
  executing"
Actors – Sending Messages


 sendAndPromise()

 Promise promise =
 replyingActor.sendAndPromise("Message 6")
 println "Got reply : ${promise.get()}"
Actors – Receiving Messages
react() method 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
Is scheduled for processing by any thread in the
thread pool once a message is available
Actors – Receiving Messages
 def calculator = Actors.actor {
   loop{
     react {a ->
       react {b ->
         println(a + b)
       }
     }
   }
 }
Blocking Actors
Blocking actors hold a single pooled thread for
their whole life-time
Includes the time when waiting for messages
Avoids thread management overhead
The number of blocking actors running
concurrently is limited by the number of threads
available in the shared pool.
Provide better performance compared to
continuation-style actors
Good candidates for high-traffic positions in actor
network.
Blocking Actors
  def decryptor = blockingActor {
  while (true) {
      receive {message ->
          if (message instanceof String)
            reply message.reverse()
          else stop()
      }
  }
  }
  def console = blockingActor {
      decryptor.send 'lellarap si yvoorG'
      println 'Decrypted message: ' + receive()
      decryptor.send false
  }
  [decryptor, console]*.join()
Stateless Actors
Dynamic Dispatch Actor

Repeatedly scans for messages

Dispatches arrived messages to one of the
onMessage(message) methods

Performance better than DefaultActor
Stateless Actors - DynamicDispatchActor
 class MyActor extends DynamicDispatchActor{

        void onMessage(String message){
          println "Received String : $message"
        }

        void onMessage(Integer message){
          println "Received Integer :
      $message"
        }

 }
Stateless Actors - DynamicDispatchActor

 Actor myActor = new
 DynamicDispatchActor().become{
   when {String msg ->
     println "Received String : $msg"
   }
   when {Integer msg ->
     println "Received Integer : $msg"
   }
 }
Stateless Actor – Static Dispatch Actor
 Contains single handler method
 Performs better than DynamicDispatchActor
 Make Dataflow operators four times faster
compared to when using DynamicDispatchActor

 class MyActor extends StaticDispatchActor<String>{
          void onMessage(String message){
               println "Message is : $message"
          }
 }
Agents
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

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


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 – Basic Rules
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.
Agents




         Example
Agent – Listeners & Validators

Listeners
Get notified each time internal state changes



Validators
Get a chance to reject a coming change by throwing an
exception
Dataflow
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 Channels

Variables

Queues

Brodcasts

Streams
Dataflow Variables

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

 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 Variables

   main         task1   task2   task3


                        x




            z           y
Benefits
 No race-conditions
 No live-locks
 Deterministic deadlocks
 Completely deterministic programs
 Beautiful Code




                                     56
Thank You

Más contenido relacionado

La actualidad más candente

Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
XSpect, a lightweight library to make your code reusable and maintainable.
XSpect, a lightweight library to make your code reusable and maintainable.XSpect, a lightweight library to make your code reusable and maintainable.
XSpect, a lightweight library to make your code reusable and maintainable.岡諭 李
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptSurvey Department
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in GroovyJim Driscoll
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationNorman Richards
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleChristopher Curtin
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 
Vavr Java User Group Rheinland
Vavr Java User Group RheinlandVavr Java User Group Rheinland
Vavr Java User Group RheinlandDavid Schmitz
 

La actualidad más candente (20)

Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
XSpect, a lightweight library to make your code reusable and maintainable.
XSpect, a lightweight library to make your code reusable and maintainable.XSpect, a lightweight library to make your code reusable and maintainable.
XSpect, a lightweight library to make your code reusable and maintainable.
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in Groovy
 
Scala
ScalaScala
Scala
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unification
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Vavr Java User Group Rheinland
Vavr Java User Group RheinlandVavr Java User Group Rheinland
Vavr Java User Group Rheinland
 

Destacado

GroovyのJSONで日付・時刻を扱う
GroovyのJSONで日付・時刻を扱うGroovyのJSONで日付・時刻を扱う
GroovyのJSONで日付・時刻を扱うYasuharu Hayami
 
GPars in Saga Groovy Study
GPars in Saga Groovy StudyGPars in Saga Groovy Study
GPars in Saga Groovy StudyNaoki Rin
 
Dataflow: the concurrency/parallelism architecture you need
Dataflow: the concurrency/parallelism architecture you needDataflow: the concurrency/parallelism architecture you need
Dataflow: the concurrency/parallelism architecture you needRussel Winder
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataCodemotion Tel Aviv
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrencyPaul King
 

Destacado (7)

GroovyのJSONで日付・時刻を扱う
GroovyのJSONで日付・時刻を扱うGroovyのJSONで日付・時刻を扱う
GroovyのJSONで日付・時刻を扱う
 
GPars in Saga Groovy Study
GPars in Saga Groovy StudyGPars in Saga Groovy Study
GPars in Saga Groovy Study
 
GPars 2014
GPars 2014GPars 2014
GPars 2014
 
Gpars Workshop 2014
Gpars Workshop 2014Gpars Workshop 2014
Gpars Workshop 2014
 
Dataflow: the concurrency/parallelism architecture you need
Dataflow: the concurrency/parallelism architecture you needDataflow: the concurrency/parallelism architecture you need
Dataflow: the concurrency/parallelism architecture you need
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
 

Similar a GPars (Groovy Parallel Systems)

Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaAD_
 
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
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with AkkaMaciej Matyjas
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matterSkills Matter
 
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetSören Stelzer
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an IntroductionRoberto Casadei
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsAndrii Lashchenko
 
Buiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with AkkaBuiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with AkkaJohan Andrén
 

Similar a GPars (Groovy Parallel Systems) (20)

G pars
G parsG pars
G pars
 
Nairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akkaNairobi JVM meetup : Introduction to akka
Nairobi JVM meetup : Introduction to akka
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Akka and futures
Akka and futuresAkka and futures
Akka and futures
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Reactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.NetReactive Programming in .Net - actorbased computing with Akka.Net
Reactive Programming in .Net - actorbased computing with Akka.Net
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
 
Akka knolx
Akka knolxAkka knolx
Akka knolx
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applications
 
Tech talk
Tech talkTech talk
Tech talk
 
Gpars workshop
Gpars workshopGpars workshop
Gpars workshop
 
Buiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with AkkaBuiilding reactive distributed systems with Akka
Buiilding reactive distributed systems with Akka
 

Más de Gagan Agrawal

Building Complex Data Workflows with Cascading on Hadoop
Building Complex Data Workflows with Cascading on HadoopBuilding Complex Data Workflows with Cascading on Hadoop
Building Complex Data Workflows with Cascading on HadoopGagan Agrawal
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and EnhancementsGagan Agrawal
 

Más de Gagan Agrawal (6)

Building Complex Data Workflows with Cascading on Hadoop
Building Complex Data Workflows with Cascading on HadoopBuilding Complex Data Workflows with Cascading on Hadoop
Building Complex Data Workflows with Cascading on Hadoop
 
Hadoop2
Hadoop2Hadoop2
Hadoop2
 
Graph db
Graph dbGraph db
Graph db
 
Hadoop
HadoopHadoop
Hadoop
 
Ast transformation
Ast transformationAst transformation
Ast transformation
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
 

Último

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Último (20)

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

GPars (Groovy Parallel Systems)

  • 2. Agenda What is Gpars? Data Parallelism Actors Agents Dataflow
  • 5. Problems with Java Concurrency Model Synchronization Dead-Locks Live-Locks Race Conditions Starvation
  • 6. GPars GOAL To fully utilize all available processors
  • 7. What is GPars ? An open-source concurrency and parallelism library for Groovy and Java Gives a number of high-level abstractions for writing concurrent and parallel code Abstractions like.. Map-Reduce Fork-Join Asynchronous Closures Actors Agents DataFlow
  • 9. Data Parallelism For low level data parallelism techniques GParsPool – Relies on JSR-166y Fork/Join Framework and offers greater functionality and better performance. GParsExecutorsPool – Uses old Java executors and so is easy to setup in a managed or restricted environment.
  • 10. Data Parallelism – Parallel Collections 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
  • 11. Parallel Collections with GParsPool 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){ .. }
  • 12. Parallel Collections with GParsPool Some of the methods supported are - eachParallel() collectParallel() findAllParallel() findAnyParallel() groupByParallel() minParallel() maxParallel() sumParallel() countParallel()
  • 13. Parallel Collections with Meta-class enhancer ParallelEnhancer def list = [1,2,3,4,5,6,7,8] ParallelEnhancer.enhanceInstance(list) println list.collectParallel{it * 2}
  • 14. Parallel Collections with Meta-class enhancer ParallelEnhancer def animals = ['dog','ant','cat','whale'] ParallelEnhancer.enhanceInstance(animals) println(animals.anyParallel{it=='ant'} ? 'Found an ant' : 'No ants found') println(animals.everyParallel{it.contains("a")} ? 'All animals contain a' : 'Some animals can live without a')
  • 15. Parallel Collections – Warning Don't do this def thumbnails = [] images.eachParallel{ thumbnails << it.thumbnail }
  • 16. Parallel Collections - Memoize Enables caching of function's return values. Repeated calls to the memoized function will retrieve the result value from an internal transparent cache. Example
  • 17. Data Parallelism – Map 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. Example
  • 18. Data Parallelism – Map Reduce How it is different from Parallel Collections The xxxParallel() methods must return a legal collection of items. Internally they build ParallelArray, perform required operation concurrently and destroy ParallelArray before returning Repeats same process for every xxxParallel() method call. With Map-Reduce Parallel Array is created just once and same is used in all chained method calls. To get collection, retrieve "collection" property
  • 19. Data Parallelism – Asynchronous Invocation async() - Creates an asynchronous variant of the supplied closure GParsPool.withPool{ Closure longLastingCalculation = {calculate()} Closure fastCalculation = longLastingCalculation.async() Future result = fastCalculation() //do stuff while calculation performs... println result.get() }
  • 20. Data Parallelism – Asynchronous Invocation callAsync() - Calls a closure in a separate thread supplying the given arguments GParsPool.withPool{ println ({it * 2}.call(3)) println ({it * 2}.callAsync(3).get()) }
  • 22. Actors Was originally inspired by the Actors library in Scala Allow for a message passing-based concurrency model 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
  • 23. Actors 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.
  • 25. Actors - Types Stateless Actors DynamicDispatchActor and Reactive Actor Keep no track of what messages have arrived previously Stateful Actors DefaultActor Allows user to handle implicit state directly After receiving a message the actor moves into a new state with different ways to handle future messages E.g Encrypted messages for decryption, only after it has received the encryption keys
  • 26. Stateful Actors Can be created in one of two ways By extending DefaultActor class Static methods of Actors class
  • 27. Actors - Usage Performs 3 specific operations Send Messages Receive Messages Create new actors
  • 28. Actors – Sending Messages Messages can be sent to actors using send() method << operator Implicit call() method
  • 29. Actors – Sending Messages def passiveActor = Actors.actor{ loop { react { msg -> println "Received: $msg"; } } } passiveActor.send 'Message 1' passiveActor << 'Message 2' passiveActor 'Message 3'
  • 30. Actors – Sending Messages sendAndWait() Blocks the caller until a reply from the actor is available.
  • 31. Actors – Sending Messages def replyingActor = Actors.actor{ loop { react { msg -> println "Received: $msg"; reply "I've got $msg" } } } def reply1 = replyingActor.sendAndWait('Message 4') def reply2 = replyingActor.sendAndWait('Message 5', 10, TimeUnit.SECONDS)
  • 32. Actors – Sending Messages sendAndContinue() replyingActor.sendAndContinue("Message 6") {reply -> println "Got reply '${reply}'" } println "I can continue while replyingActor is executing"
  • 33. Actors – Sending Messages sendAndPromise() Promise promise = replyingActor.sendAndPromise("Message 6") println "Got reply : ${promise.get()}"
  • 34. Actors – Receiving Messages react() method 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 Is scheduled for processing by any thread in the thread pool once a message is available
  • 35. Actors – Receiving Messages def calculator = Actors.actor { loop{ react {a -> react {b -> println(a + b) } } } }
  • 36. Blocking Actors Blocking actors hold a single pooled thread for their whole life-time Includes the time when waiting for messages Avoids thread management overhead The number of blocking actors running concurrently is limited by the number of threads available in the shared pool. Provide better performance compared to continuation-style actors Good candidates for high-traffic positions in actor network.
  • 37. Blocking Actors def decryptor = blockingActor { while (true) { receive {message -> if (message instanceof String) reply message.reverse() else stop() } } } def console = blockingActor { decryptor.send 'lellarap si yvoorG' println 'Decrypted message: ' + receive() decryptor.send false } [decryptor, console]*.join()
  • 38. Stateless Actors Dynamic Dispatch Actor Repeatedly scans for messages Dispatches arrived messages to one of the onMessage(message) methods Performance better than DefaultActor
  • 39. Stateless Actors - DynamicDispatchActor class MyActor extends DynamicDispatchActor{ void onMessage(String message){ println "Received String : $message" } void onMessage(Integer message){ println "Received Integer : $message" } }
  • 40. Stateless Actors - DynamicDispatchActor Actor myActor = new DynamicDispatchActor().become{ when {String msg -> println "Received String : $msg" } when {Integer msg -> println "Received Integer : $msg" } }
  • 41. Stateless Actor – Static Dispatch Actor Contains single handler method Performs better than DynamicDispatchActor Make Dataflow operators four times faster compared to when using DynamicDispatchActor class MyActor extends StaticDispatchActor<String>{ void onMessage(String message){ println "Message is : $message" } }
  • 43. 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
  • 44. Agents 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
  • 45. 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
  • 46. Agents - Basic Rules 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
  • 47. Agents – Basic Rules 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.
  • 48. Agents Example
  • 49. Agent – Listeners & Validators Listeners Get notified each time internal state changes Validators Get a chance to reject a coming change by throwing an exception
  • 51. 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
  • 53. Dataflow Variables 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
  • 54. Dataflow 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"
  • 55. Dataflow Variables main task1 task2 task3 x z y
  • 56. Benefits No race-conditions No live-locks Deterministic deadlocks Completely deterministic programs Beautiful Code 56