SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
Exploiting Concurrency
with Dynamic Languages


Tobias Ivarsson
Neo Technology
 tobias@thobe.org
Jython Committer
   @thobe on twitter
$ whoami
tobias
>   MSc in Computer Science
    from Linköping University, Sweden
>   Jython compiler zealot
>   Hacker at Neo Technology
    • Home of the Neo4j graph database
    • Check out http://neo4j.org
>   Follow me on twitter: @thobe
    • Low traffic, high tech
>   Website: http://www.thobe.org (#include blog)
                                                    2
Exploiting concurrency with dynamic languages

>   Background
>   The languages
>   The benefits of these languages
>   Example
>   Summary




                                                3
Background




             4
What Java brought to the table

>   Built in, simple support for multi threaded
    programming
>   Synchronized blocks and methods in the language
>   wait() and notify()
>   A good, sound memory model for concurrent
    situations
>   Executors, Thread pools, Concurrent collection,
    Atomic variables, Semaphores, Mutexes, Barriers,
    Latches, Exchangers, Locks, fine grained timing...

                                                        5
Why use a language other than Java?

>   More expressive - put the good stuff to better use
>   Higher order constructs abstract away tedious
    boilerplate
>   Closures




                                                         6
Why use a language other than Java?

>   Closures provide clean ways of expressing tasks
    and thread entries
>   Meta-programmability can encapsulate conventions
    • Operator overloading
    • Macros and function modifiers
>   Capabilities for building DSLs
>   Built in ways of dealing with modern problems
    • Support for concurrency best practices?

                                                       7
The Languages




                8
Jython

>   I’m biased
>   Python is used a lot in scientific computing
    • Could benefit a lot from better concurrency offered
      by Jython being on the Java platform
>   Highly dynamic
>   Strict, explicit, but compact and readable syntax




                                                           9
JRuby

>   It is a great language implementation
>   It is a popular, highly productive language
>   Highly dynamic
>   Powerful syntax for closures




                                                  10
Scala

>   Geared towards scalability in concurrency
>   Interesting Actor model
    • Provide for scalability by restricting data sharing
      between concurrently executing code




                                                            11
Clojure

>   Built at core for being good at concurrency
>   Provides for concurrency by using persistent data
    structures
    • Most objects are immutable
>   Objects that are mutable are mutated explicitly
    • Software transactional memory



                                                        12
“Why not Groovy” (or another language)

>   Good and popular dynamic language for the JVM
>   Can do anything that Java, Jython or JRuby can
>   Not interesting - All examples would be “me too”

>   Countless other languages have their specialties,
    including them all would be too much
    • Ioke, Kawa, Rhino, Java FX script, Kahlua,
      Fortress...


                                                        13
What these languages add




                           14
Automatic resource management - Jython

with synchronization_on(shared_resource):
   data = shared_resource.get_data(key)
   if data is not None:
      data.update_time = current_time()
      data.value = “The new value”
      shared_resource.set_data(key, data)




                                         15
Closures - JRuby

shared_resource.synchronized do
   data = shared_resource.get_data(key)
   if data.nil?
      data.update_time = current_time()
      data.value = “The new value”
      shared_resource.set_data key, data
   end
end


                                           16
Closures - JRuby

chunk_size = large_array.size/NUM_THREADS
threads(NUM_THREADS) do |i|
   start = chunk_size * i
   (start..start+chunk_size).each do |j|
      large_array[j] += 1
   end
end




                                        17
Meta functions - Jython (“function decorators”)

@future # start thread, return future ref
def expensive_computation(x, y):
   z = go_do_a_lot_of_stuff(x)
   return z + y

# use the function and the future
future_value = expensive_computation(4,3)
go_do_other_stuff_until_value_needed()
value = future_value()

                                                  18
Meta functions - Jython

@forkjoin # fork on call, join on iter
def recursive_iteration(root):
   if root.is_leaf:
      yield computation_on(root)
   left = recursive_iteration(root.left)
   right= recursive_iteration(root.right)
   for node in left: yield node
   for node in right: yield node
for node in recursive_iteration(tree):...

                                        19
Built in Software Transactional Memory - Clojure

(defn transfer [amount from to]
  (dosync ; isolated, atomic transaction
   (if (>= (ensure from) amount)
     (do (alter from - amount)
         (alter to + amount))
     (throw (new
             java.lang.RuntimeException
             "Insufficient funds")))))

(transfer 1000 your-account my-account)
                                                   20
Transactions as a managed resource - Jython

import neo4j
neo = neo4j.NeoService(“/var/neodb”)
persons = neo.index(“person”)
with neo.transaction:
   tobias = neo.node(name=”Tobias”)
   persons[tobias[‘name’]] = tobias
   emil = neo.node(name=”Emil”, CEO=True)
   persons[emil[‘name’]] = emil
   tobias.Knows(emil, how=”Buddies”)

                                              21
Actor Execution - Scala

>   Concurrent processes communicating through
    messages
>   Receive and act upon messages
    • Send message
    • Create new actors
    • Terminate
    • Wait for new message
>   Message objects are immutable

                                                 22
Actor Execution - Scala

case class IncredibleProblem(d:String)
class SimpleSolution(d:String)
object RichardDeanAnderson extends Actor{
   def act = {
      loop {
         react {
         case IncredibleProblem(d) =>
            reply(SimpleSolution(d))
         }}}}

                                        23
Example




          24
Adding two numbers

# Jython
def adder(a,b):
   return a+b

# JRuby
def adder(a,b)
   a+b
end


                     25
Counting the number of additions - Jython

from threading import Lock
count = 0
lock = Lock()
def adder(a,b):
   global count
   with lock:
      count += 1
   return a+b


                                            26
Counting the number of additions - JRuby

class Counting
   def adder(a,b)
      @mutex.synchronize {
         @count = @count + 1
      }
      a + b
   end
end


                                           27
Adding two numbers - Clojure

(defn adder [a b]
   (+ a b))

(let [count (ref 0)]
  (defn counting-adder [a b]
    (dosync (alter count + 1))
    (+ a b))
  (defn get-count [] (deref count)))


                                       28
Actors Adding numbers - Scala

class Adder {
  def add(a:Int,b:Int) = a+b
}




                                29
Actors Adding numbers - Scala

class Cntr(var count:Int) extends Actor {
  def act = {
    loop {
      react {
      case Inc => count = count + 1
      case GetCount => reply(count); exit
      }
    }
  } }

                                        30
Actors Adding numbers - Scala
class CountingAdder(times:Int,adder:Adder,counter:Cntr) extends Actor {
    def act = {
      loop {
        react {
	

     case Add(a,b) => {
	

       val start = nanoTime()
	

       for (i <- 0 until times) {
	

         counter ! Inc
	

         adder.add(a,b)
	

       }
	

       val time = nanoTime() - start
	

       react {
	

         case GetTime => reply(time / 1000000.0)
	

       }
	

   }
	

   case Done => exit
      } } } }

                                                                          31
Performance figures




                     32
Execution times (ms for 400000 additions)
           Jython       JRuby          Clojure

  700



  525



  350



  175



    0
                     Without counter

                                                 33
Execution times (ms for 400000 additions)
         Jython (Lock)              JRuby (Mutex)   Clojure (STM)
         Jython (AtomicInteger)
 50000



 37500



 25000



 12500



     0
                                  With counter

                                                                    34
Execution times (ms for 400000 additions)
        Mutex (JRuby)   STM (Clojure)   Actors (Scala)

 9000



 6750



 4500



 2250



    0


                                                         35
Summary




          36
Jython

>   Nice resource management syntax
>   Implementation has a few things left to work out
>   Suffer from high mutability in core datastructures




                                                         37
JRuby

>   Closures help a lot
>   Great implementation
>   Suffer from high mutability in core datastructures




                                                         38
Scala

>   Actors have good characteristics
    • Decouple work tasks with no shared state
    • Asynchronous communication is great
>   Syntax is more on the verbosity level of Java




                                                    39
Clojure

>   Immutability frees you from thinking about
    synchronization
>   Transactions for mutation enforces thinking about
    state
>   The combination enforces best practices, but in a
    way much different from “plain old Java”




                                                        40
Tobias Ivarsson
tobias@thobe.org
http://twitter.com/thobe


http://Neo4j.org

Weitere ähnliche Inhalte

Was ist angesagt?

The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
Introduction to PyTorch
Introduction to PyTorchIntroduction to PyTorch
Introduction to PyTorchJun Young Park
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its FeaturesSeiya Tokui
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningCarol McDonald
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Project Fortress
Project FortressProject Fortress
Project FortressAlex Miller
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torchRiza Fahmi
 
Optimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with TruffleOptimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with TruffleStefan Marr
 
JVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, WixJVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, WixCodemotion Tel Aviv
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJAX London
 
A synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time JavaA synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time JavaUniversidad Carlos III de Madrid
 
OpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesOpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesNarann29
 

Was ist angesagt? (20)

The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
Introduction to PyTorch
Introduction to PyTorchIntroduction to PyTorch
Introduction to PyTorch
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its Features
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Machine Trace Metrics
Machine Trace MetricsMachine Trace Metrics
Machine Trace Metrics
 
Project Fortress
Project FortressProject Fortress
Project Fortress
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torch
 
Optimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with TruffleOptimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with Truffle
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 
JVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, WixJVM Memory Model - Yoav Abrahami, Wix
JVM Memory Model - Yoav Abrahami, Wix
 
No Heap Remote Objects for Distributed real-time Java
No Heap Remote Objects for Distributed real-time JavaNo Heap Remote Objects for Distributed real-time Java
No Heap Remote Objects for Distributed real-time Java
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk Pepperdine
 
A synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time JavaA synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time Java
 
OpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesOpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering Techniques
 

Andere mochten auch

A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVMTobias Lindaaker
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVMTobias Lindaaker
 
Choosing the right NOSQL database
Choosing the right NOSQL databaseChoosing the right NOSQL database
Choosing the right NOSQL databaseTobias Lindaaker
 
Persistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4jPersistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4jTobias Lindaaker
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph DatabaseTobias Lindaaker
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming PatternMarko Rodriguez
 
An overview of Neo4j Internals
An overview of Neo4j InternalsAn overview of Neo4j Internals
An overview of Neo4j InternalsTobias Lindaaker
 
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL DatabasesDerek Stainer
 

Andere mochten auch (11)

A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
 
Choosing the right NOSQL database
Choosing the right NOSQL databaseChoosing the right NOSQL database
Choosing the right NOSQL database
 
Persistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4jPersistent graphs in Python with Neo4j
Persistent graphs in Python with Neo4j
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph Database
 
NOSQL Overview
NOSQL OverviewNOSQL Overview
NOSQL Overview
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming Pattern
 
An overview of Neo4j Internals
An overview of Neo4j InternalsAn overview of Neo4j Internals
An overview of Neo4j Internals
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
 
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL Databases
 

Ähnlich wie Exploiting Concurrency with Dynamic Languages

Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overviewstasimus
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with KotlinHaim Yadid
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Rittercatherinewall
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsSerge Stinckwich
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency ConstructsTed Leung
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法x1 ichi
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyTypesafe
 
Introductory Clojure Presentation
Introductory Clojure PresentationIntroductory Clojure Presentation
Introductory Clojure PresentationJay Victoria
 

Ähnlich wie Exploiting Concurrency with Dynamic Languages (20)

Clojure intro
Clojure introClojure intro
Clojure intro
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
MXNet Workshop
MXNet WorkshopMXNet Workshop
MXNet Workshop
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with Kotlin
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systems
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
A Survey of Concurrency Constructs
A Survey of Concurrency ConstructsA Survey of Concurrency Constructs
A Survey of Concurrency Constructs
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
Introductory Clojure Presentation
Introductory Clojure PresentationIntroductory Clojure Presentation
Introductory Clojure Presentation
 

Kürzlich hochgeladen

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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Kürzlich hochgeladen (20)

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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

Exploiting Concurrency with Dynamic Languages

  • 1. Exploiting Concurrency with Dynamic Languages Tobias Ivarsson Neo Technology tobias@thobe.org Jython Committer @thobe on twitter
  • 2. $ whoami tobias > MSc in Computer Science from Linköping University, Sweden > Jython compiler zealot > Hacker at Neo Technology • Home of the Neo4j graph database • Check out http://neo4j.org > Follow me on twitter: @thobe • Low traffic, high tech > Website: http://www.thobe.org (#include blog) 2
  • 3. Exploiting concurrency with dynamic languages > Background > The languages > The benefits of these languages > Example > Summary 3
  • 5. What Java brought to the table > Built in, simple support for multi threaded programming > Synchronized blocks and methods in the language > wait() and notify() > A good, sound memory model for concurrent situations > Executors, Thread pools, Concurrent collection, Atomic variables, Semaphores, Mutexes, Barriers, Latches, Exchangers, Locks, fine grained timing... 5
  • 6. Why use a language other than Java? > More expressive - put the good stuff to better use > Higher order constructs abstract away tedious boilerplate > Closures 6
  • 7. Why use a language other than Java? > Closures provide clean ways of expressing tasks and thread entries > Meta-programmability can encapsulate conventions • Operator overloading • Macros and function modifiers > Capabilities for building DSLs > Built in ways of dealing with modern problems • Support for concurrency best practices? 7
  • 9. Jython > I’m biased > Python is used a lot in scientific computing • Could benefit a lot from better concurrency offered by Jython being on the Java platform > Highly dynamic > Strict, explicit, but compact and readable syntax 9
  • 10. JRuby > It is a great language implementation > It is a popular, highly productive language > Highly dynamic > Powerful syntax for closures 10
  • 11. Scala > Geared towards scalability in concurrency > Interesting Actor model • Provide for scalability by restricting data sharing between concurrently executing code 11
  • 12. Clojure > Built at core for being good at concurrency > Provides for concurrency by using persistent data structures • Most objects are immutable > Objects that are mutable are mutated explicitly • Software transactional memory 12
  • 13. “Why not Groovy” (or another language) > Good and popular dynamic language for the JVM > Can do anything that Java, Jython or JRuby can > Not interesting - All examples would be “me too” > Countless other languages have their specialties, including them all would be too much • Ioke, Kawa, Rhino, Java FX script, Kahlua, Fortress... 13
  • 15. Automatic resource management - Jython with synchronization_on(shared_resource): data = shared_resource.get_data(key) if data is not None: data.update_time = current_time() data.value = “The new value” shared_resource.set_data(key, data) 15
  • 16. Closures - JRuby shared_resource.synchronized do data = shared_resource.get_data(key) if data.nil? data.update_time = current_time() data.value = “The new value” shared_resource.set_data key, data end end 16
  • 17. Closures - JRuby chunk_size = large_array.size/NUM_THREADS threads(NUM_THREADS) do |i| start = chunk_size * i (start..start+chunk_size).each do |j| large_array[j] += 1 end end 17
  • 18. Meta functions - Jython (“function decorators”) @future # start thread, return future ref def expensive_computation(x, y): z = go_do_a_lot_of_stuff(x) return z + y # use the function and the future future_value = expensive_computation(4,3) go_do_other_stuff_until_value_needed() value = future_value() 18
  • 19. Meta functions - Jython @forkjoin # fork on call, join on iter def recursive_iteration(root): if root.is_leaf: yield computation_on(root) left = recursive_iteration(root.left) right= recursive_iteration(root.right) for node in left: yield node for node in right: yield node for node in recursive_iteration(tree):... 19
  • 20. Built in Software Transactional Memory - Clojure (defn transfer [amount from to] (dosync ; isolated, atomic transaction (if (>= (ensure from) amount) (do (alter from - amount) (alter to + amount)) (throw (new java.lang.RuntimeException "Insufficient funds"))))) (transfer 1000 your-account my-account) 20
  • 21. Transactions as a managed resource - Jython import neo4j neo = neo4j.NeoService(“/var/neodb”) persons = neo.index(“person”) with neo.transaction: tobias = neo.node(name=”Tobias”) persons[tobias[‘name’]] = tobias emil = neo.node(name=”Emil”, CEO=True) persons[emil[‘name’]] = emil tobias.Knows(emil, how=”Buddies”) 21
  • 22. Actor Execution - Scala > Concurrent processes communicating through messages > Receive and act upon messages • Send message • Create new actors • Terminate • Wait for new message > Message objects are immutable 22
  • 23. Actor Execution - Scala case class IncredibleProblem(d:String) class SimpleSolution(d:String) object RichardDeanAnderson extends Actor{ def act = { loop { react { case IncredibleProblem(d) => reply(SimpleSolution(d)) }}}} 23
  • 24. Example 24
  • 25. Adding two numbers # Jython def adder(a,b): return a+b # JRuby def adder(a,b) a+b end 25
  • 26. Counting the number of additions - Jython from threading import Lock count = 0 lock = Lock() def adder(a,b): global count with lock: count += 1 return a+b 26
  • 27. Counting the number of additions - JRuby class Counting def adder(a,b) @mutex.synchronize { @count = @count + 1 } a + b end end 27
  • 28. Adding two numbers - Clojure (defn adder [a b] (+ a b)) (let [count (ref 0)] (defn counting-adder [a b] (dosync (alter count + 1)) (+ a b)) (defn get-count [] (deref count))) 28
  • 29. Actors Adding numbers - Scala class Adder { def add(a:Int,b:Int) = a+b } 29
  • 30. Actors Adding numbers - Scala class Cntr(var count:Int) extends Actor { def act = { loop { react { case Inc => count = count + 1 case GetCount => reply(count); exit } } } } 30
  • 31. Actors Adding numbers - Scala class CountingAdder(times:Int,adder:Adder,counter:Cntr) extends Actor { def act = { loop { react { case Add(a,b) => { val start = nanoTime() for (i <- 0 until times) { counter ! Inc adder.add(a,b) } val time = nanoTime() - start react { case GetTime => reply(time / 1000000.0) } } case Done => exit } } } } 31
  • 33. Execution times (ms for 400000 additions) Jython JRuby Clojure 700 525 350 175 0 Without counter 33
  • 34. Execution times (ms for 400000 additions) Jython (Lock) JRuby (Mutex) Clojure (STM) Jython (AtomicInteger) 50000 37500 25000 12500 0 With counter 34
  • 35. Execution times (ms for 400000 additions) Mutex (JRuby) STM (Clojure) Actors (Scala) 9000 6750 4500 2250 0 35
  • 36. Summary 36
  • 37. Jython > Nice resource management syntax > Implementation has a few things left to work out > Suffer from high mutability in core datastructures 37
  • 38. JRuby > Closures help a lot > Great implementation > Suffer from high mutability in core datastructures 38
  • 39. Scala > Actors have good characteristics • Decouple work tasks with no shared state • Asynchronous communication is great > Syntax is more on the verbosity level of Java 39
  • 40. Clojure > Immutability frees you from thinking about synchronization > Transactions for mutation enforces thinking about state > The combination enforces best practices, but in a way much different from “plain old Java” 40