SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Groovy Concurrency
       Alex Miller
        Revelytix
GPars
                                  Jeepers!

• Groovy library - http://gpars.codehaus.org/
• Open-source
• Great team: Václav Pech, Dierk König, Alex
  Tkachman, Russel Winder, Paul King
• Integration with Griffon, Grails, etc
Concurrency Patterns
• Asynchronous processing
• Computational processing
• Managing mutable state
 • Actor messaging
 • Agents
 • Dataflow variables
Asynchronous
    Processing

Improve perceived performance by pushing
I/O-bound work onto a different thread.
Serialized Processing
       main




      Retrieve
        user1    Twitter
       tweets




      Retrieve
        user2    Twitter
       tweets



      Process
      tweets
Asynchronous Processing

        main         background 1   background 2


    Request user1
       tweets
    Request user2      Retrieve
       tweets            user1
                        tweets        Retrieve
                                        user2
    Process tweets                     tweets
GParsExecutorsPool
•   Leverages java.util.concurrent.Executor
    •   void execute(Runnable command)

    •   Decouple task submission from task
        execution
•   GParsExecutorsPool.withPool() blocks add:
    •   async() - takes closure, returns Future
    •   callAsync() - same, but takes args
Future

• Future represents the result of an
  asynchronous computation
• Poll for results, block till available, etc
• Cancel, check for cancellation
trends.each {
   retrieveTweets(api, it.query)
}




GParsExecutorsPool.withPool {
   def retrieveTweets = {
       query -> recentTweets(api, query)
   }

    trends.each {
       retrieveTweets.callAsync(it.query)
    }
}
Computational
    Processing

Use multiple cores to reduce the elapsed
time of some cpu-bound work.
Executor Pools
Same pools used for asynch are also good
for transaction processing. Leverage more
cores to process the work.
    T1




   Task 1

                          T1       T2       T3

   Task 2


                         Task 1   Task 2   Task 3
   Task 3


                         Task 4   Task 5   Task 6
   Task 4



   Task 5



   Task 6
Work pools and
   Queues

  put           take


        queue
Fork/Join Pools

• DSL for new JSR 166y construct (JDK 7)
• DSL for ParallelArray over fork/join
• DSL for map/reduce and functional calls
Fork/Join Pools
   put           take


         queue

   put           take


         queue

   put           take


         queue
Fork/Join vs Executors
 •   Executors (GParsExecutorsPool) tuned for:
     •   small number of threads (4-16)
     •   medium-grained I/O-bound or CPU-bound
         tasks
 •   Fork/join (GParsPool) tuned for:
     •   larger number of threads (16-64)
     •   fine-grained computational tasks, possibly
         with dependencies
Divide and Conquer




   Task: Find max value in an array
Divide and Conquer
Divide and Conquer
ParallelArray
• Most business problems don’t really look
  like divide-and-conquer
• Common approach for working in parallel
  on a big data set is to use an array where
  each thread operates on independent
  chunks of the array.
• ParallelArray implements this over fork/join.
ParallelArray
 Starting orders      Order Order Order Order Order Order
  w/due dates         2/15 5/1 1/15 3/15 2/1         4/1

                      Order      Order       Order
Filter only overdue   2/15       1/15         2/1

   Map to days
                       15          45          30
    overdue

       Avg                      30 days
ParallelArray usage
def isLate = { order -> order.dueDate > new Date() }
def daysOverdue = { order -> order.daysOverdue() }

GParsPool.withPool {
  def data = createOrders()
     .filter(isLate)
     .map(daysOverdue)

    println("# overdue = " + data.size())
    println("avg overdue by = " + (data.sum() / data.size()))
}
Managing Mutable
     State
a
  The Jav
         nc y
concur re
    bible
JCIP
•   It’s the mutable state, stupid.

•   Make fields final unless they need to be mutable.

•   Immutable objects are automatically thread-safe.

•   Encapsulation makes it practical to manage the complexity.

•   Guard each mutable variable with a lock.

•   Guard all variables in an invariant with the same lock.

•   Hold locks for the duration of compound actions.

•   A program that accesses a mutable variable from multiple threads
    without synchronization is a broken program.

•   Don’t rely on clever reasoning about why you don’t need to synchronize.

•   Include thread safety in the design process - or explicitly document that
    your class is not thread-safe.

•   Document your synchronization policy.
JCIP
•   It’s the mutable state, stupid.

•   Make fields final unless they need to be mutable.

•   Immutable objects are automatically thread-safe.

•   Encapsulation makes it practical to manage the complexity.

•   Guard each mutable variable with a lock.

•   Guard all variables in an invariant with the same lock.

•   Hold locks for the duration of compound actions.

•   A program that accesses a mutable variable from multiple threads
    without synchronization is a broken program.

•   Don’t rely on clever reasoning about why you don’t need to synchronize.

•   Include thread safety in the design process - or explicitly document that
    your class is not thread-safe.

•   Document your synchronization policy.
The problem with shared state concurrency...
The problem with shared state concurrency...




            is the shared state.
Actors
• No shared state
• Lightweight processes
• Asynchronous, non-blocking message-passing
• Buffer messages in a mailbox
• Receive messages with pattern matching
• Concurrency model popular in Erlang, Scala, etc
Actors
Actors




         start
Actors

send




                start
Actors

         receive
Actor Example
class Player extends AbstractPooledActor {
  String name
  def random = new Random()

    void act() {
      loop {
        react {
          // player replies with a random move
          reply
           Move.values()[random.nextInt(Move.values().length)]
        }
      }
    }
}
Agent
• Like Clojure Agents
• Imagine wrapping an actor
  around mutable state...
• Messages are:
 • functions to apply to (internal) state OR
 • just a new value
• Can always safely retrieve value of agent
Simple example...
•   Use generics to specify data type of wrapped data
•   Pass initial value on construction
•   Send function to modify state
•   Read value by accessing val

def stuff = new Agent<List>([])

// thread 1
stuff.send( {it.add(“pizza”)} )

// thread 2
stuff.send( {it.add(“nachos”)} )

println stuff.val
class BankAccount extends Agent<Long> {
  def BankAccount() { super(0) }
  private def deposit(long deposit)
    { data += deposit }
  private def withdraw(long deposit)
    { data -= deposit }
}

final BankAccount acct = new BankAccount()

final Thread atm2 = Thread.start {
  acct << { withdraw 200 }
}

final Thread atm1 = Thread.start {
  acct << { deposit 500 }
}

[atm1,atm2]*.join()
println "Final balance: ${ acct.val }"
Dataflow Variables
• A variable that computes its value when its’
  inputs are available
• Value can be set only once
• Data flows safely between variables
• Ordering falls out automatically
• Deadlocks are deterministic
Dataflow Tasks

• Logical tasks
• Scheduled over a thread pool, like actors
• Communicate with dataflow variables
Dataflow example
final def x = new DataFlowVariable()
final def y = new DataFlowVariable()
final def z = new DataFlowVariable()

task {
    z << x.val + y.val
    println “Result: ${z.val}”
}

task {
    x << 10
}

task {
    y << 5
}
Dataflow support

• Bind handlers - can be registered on a
  dataflow variable to execute on bind
• Dataflow streams - thread-safe unbound
  blocking queue to pass data between tasks
• Dataflow operators - additional
  abstraction, formalizing inputs/outputs
Sir Not-Appearing-In-
      This-Talk

• Caching - memoize
• CSP
• GPU processing
Alex Miller

Twitter: @puredanger
Blog:      http://tech.puredanger.com
Code:
http://github.com/puredanger/gpars-examples
Conference: Strange Loop
               http://strangeloop2010.com

Weitere ähnliche Inhalte

Was ist angesagt?

Load testing Cassandra applications
Load testing Cassandra applicationsLoad testing Cassandra applications
Load testing Cassandra applicationsBen Slater
 
Speed Up Your Existing Relational Databases with Hazelcast and Speedment
Speed Up Your Existing Relational Databases with Hazelcast and SpeedmentSpeed Up Your Existing Relational Databases with Hazelcast and Speedment
Speed Up Your Existing Relational Databases with Hazelcast and SpeedmentHazelcast
 
DZone Java 8 Block Buster: Query Databases Using Streams
DZone Java 8 Block Buster: Query Databases Using StreamsDZone Java 8 Block Buster: Query Databases Using Streams
DZone Java 8 Block Buster: Query Databases Using StreamsSpeedment, Inc.
 
Think Distributed: The Hazelcast Way
Think Distributed: The Hazelcast WayThink Distributed: The Hazelcast Way
Think Distributed: The Hazelcast WayRahul Gupta
 
Hazelcast Essentials
Hazelcast EssentialsHazelcast Essentials
Hazelcast EssentialsRahul Gupta
 
M6d cassandrapresentation
M6d cassandrapresentationM6d cassandrapresentation
M6d cassandrapresentationEdward Capriolo
 
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...DataStax
 
Practicing Continuous Deployment
Practicing Continuous DeploymentPracticing Continuous Deployment
Practicing Continuous Deploymentzeeg
 
Webinar: Getting Started with Apache Cassandra
Webinar: Getting Started with Apache CassandraWebinar: Getting Started with Apache Cassandra
Webinar: Getting Started with Apache CassandraDataStax
 
NYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ SpeedmentNYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ SpeedmentSpeedment, Inc.
 
Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...
Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...
Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...DataStax
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeperknowbigdata
 
Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...
Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...
Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...DataStax
 
Geek Nights Hong Kong
Geek Nights Hong KongGeek Nights Hong Kong
Geek Nights Hong KongRahul Gupta
 
Loadays MySQL
Loadays MySQLLoadays MySQL
Loadays MySQLlefredbe
 
High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016Vlad Mihalcea
 
Divide and conquer in the cloud
Divide and conquer in the cloudDivide and conquer in the cloud
Divide and conquer in the cloudJustin Swanhart
 
Using apache spark for processing trillions of records each day at Datadog
Using apache spark for processing trillions of records each day at DatadogUsing apache spark for processing trillions of records each day at Datadog
Using apache spark for processing trillions of records each day at DatadogVadim Semenov
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into CassandraBrian Hess
 
Cassandra Summit 2015: Intro to DSE Search
Cassandra Summit 2015: Intro to DSE SearchCassandra Summit 2015: Intro to DSE Search
Cassandra Summit 2015: Intro to DSE SearchCaleb Rackliffe
 

Was ist angesagt? (20)

Load testing Cassandra applications
Load testing Cassandra applicationsLoad testing Cassandra applications
Load testing Cassandra applications
 
Speed Up Your Existing Relational Databases with Hazelcast and Speedment
Speed Up Your Existing Relational Databases with Hazelcast and SpeedmentSpeed Up Your Existing Relational Databases with Hazelcast and Speedment
Speed Up Your Existing Relational Databases with Hazelcast and Speedment
 
DZone Java 8 Block Buster: Query Databases Using Streams
DZone Java 8 Block Buster: Query Databases Using StreamsDZone Java 8 Block Buster: Query Databases Using Streams
DZone Java 8 Block Buster: Query Databases Using Streams
 
Think Distributed: The Hazelcast Way
Think Distributed: The Hazelcast WayThink Distributed: The Hazelcast Way
Think Distributed: The Hazelcast Way
 
Hazelcast Essentials
Hazelcast EssentialsHazelcast Essentials
Hazelcast Essentials
 
M6d cassandrapresentation
M6d cassandrapresentationM6d cassandrapresentation
M6d cassandrapresentation
 
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
Optimizing Your Cluster with Coordinator Nodes (Eric Lubow, SimpleReach) | Ca...
 
Practicing Continuous Deployment
Practicing Continuous DeploymentPracticing Continuous Deployment
Practicing Continuous Deployment
 
Webinar: Getting Started with Apache Cassandra
Webinar: Getting Started with Apache CassandraWebinar: Getting Started with Apache Cassandra
Webinar: Getting Started with Apache Cassandra
 
NYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ SpeedmentNYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ Speedment
 
Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...
Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...
Operations, Consistency, Failover for Multi-DC Clusters (Alexander Dejanovski...
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...
Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...
Clock Skew and Other Annoying Realities in Distributed Systems (Donny Nadolny...
 
Geek Nights Hong Kong
Geek Nights Hong KongGeek Nights Hong Kong
Geek Nights Hong Kong
 
Loadays MySQL
Loadays MySQLLoadays MySQL
Loadays MySQL
 
High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016
 
Divide and conquer in the cloud
Divide and conquer in the cloudDivide and conquer in the cloud
Divide and conquer in the cloud
 
Using apache spark for processing trillions of records each day at Datadog
Using apache spark for processing trillions of records each day at DatadogUsing apache spark for processing trillions of records each day at Datadog
Using apache spark for processing trillions of records each day at Datadog
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into Cassandra
 
Cassandra Summit 2015: Intro to DSE Search
Cassandra Summit 2015: Intro to DSE SearchCassandra Summit 2015: Intro to DSE Search
Cassandra Summit 2015: Intro to DSE Search
 

Andere mochten auch

Project Fortress
Project FortressProject Fortress
Project FortressAlex Miller
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebAlex Miller
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative SoftwareAlex Miller
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinAlex Miller
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojureAlex Miller
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
Visualising Data on Interactive Maps
Visualising Data on Interactive MapsVisualising Data on Interactive Maps
Visualising Data on Interactive MapsAnna Pawlicka
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaRussel Winder
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Kyung Koo Yoon
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
concurrency gpars
concurrency gparsconcurrency gpars
concurrency gparsPaul King
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrencyPaul King
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009Alex Miller
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with ZippersAlex Miller
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream ProcessingAlex Miller
 
Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Alex Miller
 

Andere mochten auch (20)

Project Fortress
Project FortressProject Fortress
Project Fortress
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic Web
 
Blogging ZOMG
Blogging ZOMGBlogging ZOMG
Blogging ZOMG
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative Software
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/join
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojure
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Visualising Data on Interactive Maps
Visualising Data on Interactive MapsVisualising Data on Interactive Maps
Visualising Data on Interactive Maps
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for Java
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
concurrency gpars
concurrency gparsconcurrency gpars
concurrency gpars
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream Processing
 
Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)
 

Ähnlich wie Groovy Concurrency Patterns

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsKevin Webber
 
NetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksNetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksRuslan Meshenberg
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Mike Slinn
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersNLJUG
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with EpsilonSina Madani
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flinkRenato Guimaraes
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormDavorin Vukelic
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Jimmy Lai
 
Benchmarking Solr Performance at Scale
Benchmarking Solr Performance at ScaleBenchmarking Solr Performance at Scale
Benchmarking Solr Performance at Scalethelabdude
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a clusterGal Marder
 
Continuous Application with FAIR Scheduler with Robert Xue
Continuous Application with FAIR Scheduler with Robert XueContinuous Application with FAIR Scheduler with Robert Xue
Continuous Application with FAIR Scheduler with Robert XueDatabricks
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer mcwilson1
 
Functional Programming and Composing Actors
Functional Programming and Composing ActorsFunctional Programming and Composing Actors
Functional Programming and Composing Actorslegendofklang
 

Ähnlich wie Groovy Concurrency Patterns (20)

G pars
G parsG pars
G pars
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
NetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksNetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talks
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with Epsilon
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flink
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...
 
Benchmarking Solr Performance at Scale
Benchmarking Solr Performance at ScaleBenchmarking Solr Performance at Scale
Benchmarking Solr Performance at Scale
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
 
Continuous Application with FAIR Scheduler with Robert Xue
Continuous Application with FAIR Scheduler with Robert XueContinuous Application with FAIR Scheduler with Robert Xue
Continuous Application with FAIR Scheduler with Robert Xue
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
Functional Programming and Composing Actors
Functional Programming and Composing ActorsFunctional Programming and Composing Actors
Functional Programming and Composing Actors
 

Mehr von Alex Miller

Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleAlex Miller
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow TestAlex Miller
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns ReconsideredAlex Miller
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring TerracottaAlex Miller
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 

Mehr von Alex Miller (8)

Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At Scale
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow Test
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
 
Java 7 Preview
Java 7 PreviewJava 7 Preview
Java 7 Preview
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring Terracotta
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 

Kürzlich hochgeladen

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
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
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
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
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
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
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
 

Kürzlich hochgeladen (20)

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
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
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
 
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
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
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
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
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.
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
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
 

Groovy Concurrency Patterns

  • 1. Groovy Concurrency Alex Miller Revelytix
  • 2. GPars Jeepers! • Groovy library - http://gpars.codehaus.org/ • Open-source • Great team: Václav Pech, Dierk König, Alex Tkachman, Russel Winder, Paul King • Integration with Griffon, Grails, etc
  • 3. Concurrency Patterns • Asynchronous processing • Computational processing • Managing mutable state • Actor messaging • Agents • Dataflow variables
  • 4. Asynchronous Processing Improve perceived performance by pushing I/O-bound work onto a different thread.
  • 5. Serialized Processing main Retrieve user1 Twitter tweets Retrieve user2 Twitter tweets Process tweets
  • 6. Asynchronous Processing main background 1 background 2 Request user1 tweets Request user2 Retrieve tweets user1 tweets Retrieve user2 Process tweets tweets
  • 7. GParsExecutorsPool • Leverages java.util.concurrent.Executor • void execute(Runnable command) • Decouple task submission from task execution • GParsExecutorsPool.withPool() blocks add: • async() - takes closure, returns Future • callAsync() - same, but takes args
  • 8. Future • Future represents the result of an asynchronous computation • Poll for results, block till available, etc • Cancel, check for cancellation
  • 9. trends.each { retrieveTweets(api, it.query) } GParsExecutorsPool.withPool { def retrieveTweets = { query -> recentTweets(api, query) } trends.each { retrieveTweets.callAsync(it.query) } }
  • 10. Computational Processing Use multiple cores to reduce the elapsed time of some cpu-bound work.
  • 11. Executor Pools Same pools used for asynch are also good for transaction processing. Leverage more cores to process the work. T1 Task 1 T1 T2 T3 Task 2 Task 1 Task 2 Task 3 Task 3 Task 4 Task 5 Task 6 Task 4 Task 5 Task 6
  • 12. Work pools and Queues put take queue
  • 13. Fork/Join Pools • DSL for new JSR 166y construct (JDK 7) • DSL for ParallelArray over fork/join • DSL for map/reduce and functional calls
  • 14. Fork/Join Pools put take queue put take queue put take queue
  • 15. Fork/Join vs Executors • Executors (GParsExecutorsPool) tuned for: • small number of threads (4-16) • medium-grained I/O-bound or CPU-bound tasks • Fork/join (GParsPool) tuned for: • larger number of threads (16-64) • fine-grained computational tasks, possibly with dependencies
  • 16. Divide and Conquer Task: Find max value in an array
  • 19. ParallelArray • Most business problems don’t really look like divide-and-conquer • Common approach for working in parallel on a big data set is to use an array where each thread operates on independent chunks of the array. • ParallelArray implements this over fork/join.
  • 20. ParallelArray Starting orders Order Order Order Order Order Order w/due dates 2/15 5/1 1/15 3/15 2/1 4/1 Order Order Order Filter only overdue 2/15 1/15 2/1 Map to days 15 45 30 overdue Avg 30 days
  • 21. ParallelArray usage def isLate = { order -> order.dueDate > new Date() } def daysOverdue = { order -> order.daysOverdue() } GParsPool.withPool { def data = createOrders() .filter(isLate) .map(daysOverdue) println("# overdue = " + data.size()) println("avg overdue by = " + (data.sum() / data.size())) }
  • 23. a The Jav nc y concur re bible
  • 24. JCIP • It’s the mutable state, stupid. • Make fields final unless they need to be mutable. • Immutable objects are automatically thread-safe. • Encapsulation makes it practical to manage the complexity. • Guard each mutable variable with a lock. • Guard all variables in an invariant with the same lock. • Hold locks for the duration of compound actions. • A program that accesses a mutable variable from multiple threads without synchronization is a broken program. • Don’t rely on clever reasoning about why you don’t need to synchronize. • Include thread safety in the design process - or explicitly document that your class is not thread-safe. • Document your synchronization policy.
  • 25. JCIP • It’s the mutable state, stupid. • Make fields final unless they need to be mutable. • Immutable objects are automatically thread-safe. • Encapsulation makes it practical to manage the complexity. • Guard each mutable variable with a lock. • Guard all variables in an invariant with the same lock. • Hold locks for the duration of compound actions. • A program that accesses a mutable variable from multiple threads without synchronization is a broken program. • Don’t rely on clever reasoning about why you don’t need to synchronize. • Include thread safety in the design process - or explicitly document that your class is not thread-safe. • Document your synchronization policy.
  • 26. The problem with shared state concurrency...
  • 27. The problem with shared state concurrency... is the shared state.
  • 28. Actors • No shared state • Lightweight processes • Asynchronous, non-blocking message-passing • Buffer messages in a mailbox • Receive messages with pattern matching • Concurrency model popular in Erlang, Scala, etc
  • 30. Actors start
  • 31. Actors send start
  • 32. Actors receive
  • 33. Actor Example class Player extends AbstractPooledActor { String name def random = new Random() void act() { loop { react { // player replies with a random move reply Move.values()[random.nextInt(Move.values().length)] } } } }
  • 34. Agent • Like Clojure Agents • Imagine wrapping an actor around mutable state... • Messages are: • functions to apply to (internal) state OR • just a new value • Can always safely retrieve value of agent
  • 35. Simple example... • Use generics to specify data type of wrapped data • Pass initial value on construction • Send function to modify state • Read value by accessing val def stuff = new Agent<List>([]) // thread 1 stuff.send( {it.add(“pizza”)} ) // thread 2 stuff.send( {it.add(“nachos”)} ) println stuff.val
  • 36. class BankAccount extends Agent<Long> { def BankAccount() { super(0) } private def deposit(long deposit) { data += deposit } private def withdraw(long deposit) { data -= deposit } } final BankAccount acct = new BankAccount() final Thread atm2 = Thread.start { acct << { withdraw 200 } } final Thread atm1 = Thread.start { acct << { deposit 500 } } [atm1,atm2]*.join() println "Final balance: ${ acct.val }"
  • 37. Dataflow Variables • A variable that computes its value when its’ inputs are available • Value can be set only once • Data flows safely between variables • Ordering falls out automatically • Deadlocks are deterministic
  • 38. Dataflow Tasks • Logical tasks • Scheduled over a thread pool, like actors • Communicate with dataflow variables
  • 39. Dataflow example final def x = new DataFlowVariable() final def y = new DataFlowVariable() final def z = new DataFlowVariable() task { z << x.val + y.val println “Result: ${z.val}” } task { x << 10 } task { y << 5 }
  • 40. Dataflow support • Bind handlers - can be registered on a dataflow variable to execute on bind • Dataflow streams - thread-safe unbound blocking queue to pass data between tasks • Dataflow operators - additional abstraction, formalizing inputs/outputs
  • 41. Sir Not-Appearing-In- This-Talk • Caching - memoize • CSP • GPU processing
  • 42. Alex Miller Twitter: @puredanger Blog: http://tech.puredanger.com Code: http://github.com/puredanger/gpars-examples Conference: Strange Loop http://strangeloop2010.com