SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PDF
The Evolution of Async-Programming on .NET Platform (TUP, Full)
jeffz
 
PDF
Javascript engine performance
Duoyi Wu
 
PPTX
Introduction to PyTorch
Jun Young Park
 
PDF
Overview of Chainer and Its Features
Seiya Tokui
 
PPTX
Node.js System: The Landing
Haci Murat Yaman
 
ODP
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
PPTX
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
PDF
Blocks & GCD
rsebbe
 
PDF
Machine Trace Metrics
Wang Hsiangkai
 
PDF
Project Fortress
Alex Miller
 
PDF
Machine learning with py torch
Riza Fahmi
 
PPTX
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
PDF
04 - Qt Data
Andreas Jakl
 
PPTX
JVM Memory Model - Yoav Abrahami, Wix
Codemotion Tel Aviv
 
PPT
No Heap Remote Objects for Distributed real-time Java
Universidad Carlos III de Madrid
 
PDF
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
PPT
Deuce STM - CMP'09
Guy Korland
 
KEY
Java and the machine - Martijn Verburg and Kirk Pepperdine
JAX London
 
PPT
A synchronous scheduling service for distributed real-time Java
Universidad Carlos III de Madrid
 
PDF
OpenGL 4.4 - Scene Rendering Techniques
Narann29
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
jeffz
 
Javascript engine performance
Duoyi Wu
 
Introduction to PyTorch
Jun Young Park
 
Overview of Chainer and Its Features
Seiya Tokui
 
Node.js System: The Landing
Haci Murat Yaman
 
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
Pune-Cocoa: Blocks and GCD
Prashant Rane
 
Blocks & GCD
rsebbe
 
Machine Trace Metrics
Wang Hsiangkai
 
Project Fortress
Alex Miller
 
Machine learning with py torch
Riza Fahmi
 
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
04 - Qt Data
Andreas Jakl
 
JVM Memory Model - Yoav Abrahami, Wix
Codemotion Tel Aviv
 
No Heap Remote Objects for Distributed real-time Java
Universidad Carlos III de Madrid
 
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
Deuce STM - CMP'09
Guy Korland
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
JAX London
 
A synchronous scheduling service for distributed real-time Java
Universidad Carlos III de Madrid
 
OpenGL 4.4 - Scene Rendering Techniques
Narann29
 

Viewers also liked (11)

PDF
A Better Python for the JVM
Tobias Lindaaker
 
PDF
JDK Power Tools
Tobias Lindaaker
 
PDF
A Better Python for the JVM
Tobias Lindaaker
 
PDF
Choosing the right NOSQL database
Tobias Lindaaker
 
PDF
Persistent graphs in Python with Neo4j
Tobias Lindaaker
 
PDF
Building Applications with a Graph Database
Tobias Lindaaker
 
PDF
NOSQL Overview
Tobias Lindaaker
 
PDF
The Graph Traversal Programming Pattern
Marko Rodriguez
 
PDF
An overview of Neo4j Internals
Tobias Lindaaker
 
PPT
Mixing Python and Java
Andreas Schreiber
 
PPTX
Introduction to NoSQL Databases
Derek Stainer
 
A Better Python for the JVM
Tobias Lindaaker
 
JDK Power Tools
Tobias Lindaaker
 
A Better Python for the JVM
Tobias Lindaaker
 
Choosing the right NOSQL database
Tobias Lindaaker
 
Persistent graphs in Python with Neo4j
Tobias Lindaaker
 
Building Applications with a Graph Database
Tobias Lindaaker
 
NOSQL Overview
Tobias Lindaaker
 
The Graph Traversal Programming Pattern
Marko Rodriguez
 
An overview of Neo4j Internals
Tobias Lindaaker
 
Mixing Python and Java
Andreas Schreiber
 
Introduction to NoSQL Databases
Derek Stainer
 
Ad

Similar to Exploiting Concurrency with Dynamic Languages (20)

PDF
Clojure intro
Basav Nagur
 
PDF
Exploring Clojurescript
Luke Donnet
 
PPTX
Concurrency Constructs Overview
stasimus
 
PDF
Clojure made-simple - John Stevenson
JAX London
 
PPTX
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson
 
PDF
Building microservices with Kotlin
Haim Yadid
 
ODP
Getting started with Clojure
John Stevenson
 
PDF
Java Future S Ritter
catherinewall
 
PPTX
Clojure And Swing
Skills Matter
 
PPTX
.NET Multithreading/Multitasking
Sasha Kravchuk
 
PDF
Groovy concurrency
Alex Miller
 
KEY
Using Smalltalk for controlling robotics systems
Serge Stinckwich
 
PPTX
Practical LLM inference in modern Java.pptx
Alina Yurenko
 
PPTX
Practical LLM inference in modern Java.pptx
Alina Yurenko
 
PDF
Introduction to clojure
Abbas Raza
 
PDF
A Survey of Concurrency Constructs
Ted Leung
 
PPSX
Java Tutorial
Akash Pandey
 
PDF
Clojure - A new Lisp
elliando dias
 
PDF
あなたのScalaを爆速にする7つの方法
x1 ichi
 
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Clojure intro
Basav Nagur
 
Exploring Clojurescript
Luke Donnet
 
Concurrency Constructs Overview
stasimus
 
Clojure made-simple - John Stevenson
JAX London
 
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson
 
Building microservices with Kotlin
Haim Yadid
 
Getting started with Clojure
John Stevenson
 
Java Future S Ritter
catherinewall
 
Clojure And Swing
Skills Matter
 
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Groovy concurrency
Alex Miller
 
Using Smalltalk for controlling robotics systems
Serge Stinckwich
 
Practical LLM inference in modern Java.pptx
Alina Yurenko
 
Practical LLM inference in modern Java.pptx
Alina Yurenko
 
Introduction to clojure
Abbas Raza
 
A Survey of Concurrency Constructs
Ted Leung
 
Java Tutorial
Akash Pandey
 
Clojure - A new Lisp
elliando dias
 
あなたのScalaを爆速にする7つの方法
x1 ichi
 
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Ad

Recently uploaded (20)

PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 

Exploiting Concurrency with Dynamic Languages

  • 1. Exploiting Concurrency with Dynamic Languages Tobias Ivarsson Neo Technology [email protected] 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