SlideShare a Scribd company logo
Models for Concurrent
   Programming

                          tobias@neotechnology.com
Tobias Ivarsson           twitter: @thobe
                          web: http://thobe.org/ http://neo4j.org/
hacker @ Neo Technology
Common misconceptions


                   2
More threads
      ==
More throughput

                  3
Finite number of cores


                    4
Other limiting factors
 f.ex. I/O is only one pipe


                              5
Locking always impedes performance




                              6
Concurrency on
 the track, only
   one in the
     station

           7
Amdahl’s law
                   1
      Speedup ≤
                       1-F
                  F+
                       N



         N: Number of processors
         F: Serial fraction
                                   8
Throughput with
Throughput: 3
                 synchronized
                    regions

                            9
Throughput with
Throughput: 6
                      synchronized
                         regions
           wait...




                                 9
Throughput with
                            synchronized
Throughput: 9

                               regions
           wait...
                     wait...




                                       9
Throughput with
                           synchronized
Throughput: 11
                              regions
          wait...
                    wait...
                              wait...



                                        9
Throughput with
                           synchronized
Throughput: 11                regions
                                                  wait...                                           wait...
          wait...                                           wait...                                           wait...
                    wait...                                           wait...
                              wait...                                           wait...
                                        wait...                                           wait...


                                                                                                    10
Throughput with
                           synchronized
                              regions
Throughput: 11

                                                       wait...
          wait...                                                wait...
                    wait...
                              wait...
                                        wait...
                                             wait...
                                                                           11
The fundamentals
 ą¹Threads
 ą¹Mutual exclusion
    synchronization and locks

 ą¹Java Memory Model
    read/write barriers & publication



                                        12
The Java Memory Model                      1 33
         What you need to know            JSR
ą¹   Visibility / Publication of objects/fields
ą¹   (Un)Acceptable out-of-order behavior
    i.e. guarantees about ordering
ą¹ Implementations based on the
    hardware MM of the target platform


                                          13
Concurrency abstractions


                     14
Java as we know it


                     15
Threads
ą¹ Abstract the line of excution from the CPU(s)
ą¹ Provided by most (all mainstream) operating systems
ą¹ CPU execution can continue on another thread if
   one thread blocks


ą¹ Increases CPU utilization

                                                16
Monitors
synchronized (someMonitor)
{ read barrier
     // single threaded region
} write barrier




                                 17
Volatile read/write


                      18
class Thing {
    volatile String name;
    String getName() {
        return this.name; read barrier
    }
    void setName( String newName ) {
        this.name = newName; write barrier

}
    }
        ą¹ Guarantees visibility:
            always read the latest value

        ą¹Guarantees safe publication:
            no re-ordering of
            pre-write ops with
            post-write ops                   19
Monitors
synchronized (someMonitor)
{ read barrier
     // single threaded region
} write barrier
       ą¹Writes may not be
           reordered across the end

       ą¹Reads may not be
           reordered across the start
                                        20
java.util.concurrent


                   21
ConcurrentMap<String,Thing> map =
 new ConcurrentHashMap();
   ą¹Adds atomic operations to the Map
     interface:
    - putIfAbsent(key, value)
    - remove(key, value)
    - replace(key,[oldVal,]newVal)
    - but not yet
       putIfAbsent(key, #{makeValue()})
  ą¹CHM is lock striped, i.e. synchronized
     on regions                         22
List<Thing> list = new
 CopyOnWriteArrayList();
ą¹Synchronize writers,
   unrestricted readers
ą¹Good for: #reads >> #writes
ą¹Readers get snapshot state:
   gives stable iteration
ą¹Volatile variable for immutable
   state to ensure publication     23
public class CopyOnWriteArrayList<T>
private volatile Object[] array = new Object[0];


public synchronized boolean add(T value) {
   Object[] newArray = Arrays.copyOf(array, array.length+1);
   newArray[array.length] = value;
   array = newArray; // write barrier
   return true;
} // write barrier


public Iterator<T> iterator() {
   return new ArrayIterator<T>(this.array); // read barrier
}


private static class ArrayIterator<T> implements Iterator<T> {
   // I’ve written too many of these to be amused any more ...
}
                                                         24
ExecutorService executor = new
  ThreadPoolExecutor();

executor.submit(new Runnable() {
                   ą¹
    void run() {
        doWork();   Focus on tasks - not threads
    }
});                ą¹Mitigate thread start/stop
                       overhead

                   ą¹Ensure a balanced number
                       of threads for the target
                       platform
                                           25
java.util.concurrent.locks


                       26
LockSupport.park();         // currentThread


LockSupport.unpark(Thread t);
  ą¹The thread will ā€œsleepā€ until unparked
  ą¹Although unpark-before-park marks
     the thread as unparked, returning
     from park immediately
  ą¹... and there’s still the chance of
     spurious wakeups ...
  ą¹Too low level for most people         27
Lock lock = new ReentrantLock();

ReadWriteLock rwLock = new ReentrantReadWriteLock();

Lock read = rwLock.readLock();
                                // Two related locks
Lock write = rwLock.writeLock();

  lock.lock();
  try { doWork() } finally { lock.unlock(); }

  if ( lock.tryLock() )
     try { doWork() } finally { lock.unlock(); }
  else
     backOffAndTryAgainLater();

                                             28
java.util.concurrent.atomic


                        29
AtomicReference<Thing> ref = new AtomicReference();

AtomicReferenceArray<Thing> array = new AtomicReferenceArray();




                                                         30
AtomicReference<Thing> ref = new AtomicReference();

AtomicReferenceArray<Thing> array = new AtomicReferenceArray();

   class MyAtomicThingReference {
       volatile Thing thing;
       static AtomicReferenceFieldUpdater
        <MyAtomicThingReference,Thing> THING = newUpdater(...);

       Thing swap( Thing newThing ) {
           return THING.getAndSet( this, newThing );
       }

 ą¹Atomic* gives you compareAndSet()
   }



 ą¹Atomic*Updater saves indirection:
  ą¹One less object header - less memory
  ą¹One read-address-get-object operation:
        better cache locality
                                                         30
Java of Tomorrow
(actually Today, JDK7 is already out)




                                        31
ForkJoin
ą¹More ā€œadvancedā€ Executor
ą¹Assumes/requires more of
  the tasks it runs
ą¹Tasks first split into multiple
  sub-tasks, push on stack
ą¹Idle workers ā€œstealā€ work
  from the bottom of the
  stack of other workers
                                  32
Models not in Java today


                     33
ParallelArray


                34
ParallelArray<Student> students = ...

double highestScore = students
    .filter( #{ Student s -> s.gradYear == 2010 } )
    .map(    #{ Student s -> s.score } )
    .max();




                                            35
Transactional Memory


                  36
void transfer( TransactionalLong source,
               TransactionalLong target,
               long amount ) {

    try ( Transaction tx = txManager.beingTransaction() ) {

        long sourceFunds = source.getValue();
        if (sourceFunds < amount) {
          throw new InsufficientFundsException();
        }
        source.setValue( sourceFunds - amount );
        target.setValue( target.getValue() + amount );

        tx.success();
    }

}
                                                     37
Actors


         38
class SimpleActor extends Actor {
  var state
  def receive = {
    case Get => self reply state
    case Set(newState) => state = newState
  }
}




                                  geā€
                                ans
                               ssa
                      ā€œse s me
                            me
                         nd
                          i
                        Th
val response = simple !! Set( "new state" )



                                        39
Scala Parallel
Collection Framework

                  40
Efficient Collection
splitting & combining



                    41
Efficient Collection
splitting & combining



                    41
Efficient Collection
splitting & combining



                    41
Efficient Collection
splitting & combining



                    41
Splittable maps
            15



        5        174



    2       8




                       42
Splittable maps
    8       5   15




        2            174




                           43
Hash tries
ą¹Similar performance to hash
   tables

ą¹Splittable (like arrays)
ą¹Memory (re)allocation
   more like trees

ą¹No resizing races
                               44
Clojure


          45
Immutable by default


                   46
Thread local
(and scoped)
  override
               47
(def x 10) ; create a root binding


(def x 42) ; redefine the root binding


(binding [x 13] ...) ; create a thread local override




                                              48
Transactional memory
(ref) and (dosync ...)


                    49
(def street (ref))
(def city (ref))


(defn move [new-street new-city]
  (dosync ; synchronize the changes
    (ref-set street new-street)
    (ref-set city new-city)))
; will retry if txn fails due to concurrent change


(defn print-address []
  (dosync ; get a snapshot state of the refs
    (printf "I live on %s in %s%n" @street @city)))




                                               50
(atom)
easier API for AtomicReference


                           51
(defstruct address-t :street :city)


(def address (atom))


(defn move [new-street new-city]
  (set address
    (struct address-t new-street new-city)))


(defn print-address []
  (let [addr @address] ; get snapshot
    (printf "I live on %s in %s%n"
            (get addr :street)
            (get addr :city))))

                                               52
Explicit asynchronous updates



                          53
(agent)
A simpler cousin to actors


                         54
(def account (agent))


(defn deposit [balance amount]
   (+ balance amount))

(send account deposit 1000)


                              55
we’re hiring
http://neotechnology.com/about-us/jobs




           http://neotechnology.com
Questions?

More Related Content

What's hot (20)

PPTX
Node.js System: The Landing
Haci Murat Yaman
Ā 
PDF
Blocks & GCD
rsebbe
Ā 
KEY
Java and the machine - Martijn Verburg and Kirk Pepperdine
JAX London
Ā 
PDF
To Swift 2...and Beyond!
Scott Gardner
Ā 
PDF
Machine Trace Metrics
Wang Hsiangkai
Ā 
PDF
04 - Qt Data
Andreas Jakl
Ā 
ODP
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
Ā 
PPT
No Heap Remote Objects for Distributed real-time Java
Universidad Carlos III de Madrid
Ā 
PDF
Overview of Chainer and Its Features
Seiya Tokui
Ā 
PPTX
Pune-Cocoa: Blocks and GCD
Prashant Rane
Ā 
PDF
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
Ā 
PPT
A synchronous scheduling service for distributed real-time Java
Universidad Carlos III de Madrid
Ā 
PPT
Enhancing the region model of RTSJ
Universidad Carlos III de Madrid
Ā 
PPT
Basanta jtr2009
Universidad Carlos III de Madrid
Ā 
PPTX
Introduction to PyTorch
Jun Young Park
Ā 
PDF
06 - Qt Communication
Andreas Jakl
Ā 
PPT
Deuce STM - CMP'09
Guy Korland
Ā 
PDF
Project Fortress
Alex Miller
Ā 
PDF
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
Ā 
PPT
Simple asynchronous remote invocations for distributed real-time Java
Universidad Carlos III de Madrid
Ā 
Node.js System: The Landing
Haci Murat Yaman
Ā 
Blocks & GCD
rsebbe
Ā 
Java and the machine - Martijn Verburg and Kirk Pepperdine
JAX London
Ā 
To Swift 2...and Beyond!
Scott Gardner
Ā 
Machine Trace Metrics
Wang Hsiangkai
Ā 
04 - Qt Data
Andreas Jakl
Ā 
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
Ā 
No Heap Remote Objects for Distributed real-time Java
Universidad Carlos III de Madrid
Ā 
Overview of Chainer and Its Features
Seiya Tokui
Ā 
Pune-Cocoa: Blocks and GCD
Prashant Rane
Ā 
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
Ā 
A synchronous scheduling service for distributed real-time Java
Universidad Carlos III de Madrid
Ā 
Enhancing the region model of RTSJ
Universidad Carlos III de Madrid
Ā 
Introduction to PyTorch
Jun Young Park
Ā 
06 - Qt Communication
Andreas Jakl
Ā 
Deuce STM - CMP'09
Guy Korland
Ā 
Project Fortress
Alex Miller
Ā 
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
Ā 
Simple asynchronous remote invocations for distributed real-time Java
Universidad Carlos III de Madrid
Ā 

Viewers also liked (11)

PDF
A Better Python for the JVM
Tobias Lindaaker
Ā 
PDF
A Better Python for the JVM
Tobias Lindaaker
Ā 
PDF
JDK Power Tools
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
Ā 
A Better Python for the JVM
Tobias Lindaaker
Ā 
JDK Power Tools
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 [JavaOne 2011] Models for Concurrent Programming (20)

PPTX
opt-mem-trx
Miguel Gamboa
Ā 
PDF
Twisted
Michal Sedlak
Ā 
PPTX
Medical Image Processing Strategies for multi-core CPUs
Daniel Blezek
Ā 
PDF
Java Runtime: повсеГневные Š¾Š±ŃŠ·Š°Š½Š½Š¾ŃŃ‚Šø JVM
odnoklassniki.ru
Ā 
PDF
Java Concurrency in Practice
Alina Dolgikh
Ā 
PDF
Scaling Apache Storm - Strata + Hadoop World 2014
P. Taylor Goetz
Ā 
PDF
Metasploit Basics
amiable_indian
Ā 
PDF
Let's Talk Locks!
C4Media
Ā 
PDF
Programming with Threads in Java
koji lin
Ā 
PDF
[Blackhat EU'14] Attacking the Linux PRNG on Android and Embedded Devices
srkedmi
Ā 
PPT
Nodejs Intro Part One
Budh Ram Gurung
Ā 
PPTX
Async fun
šŸ’” Tomasz Kogut
Ā 
PPTX
Effective java - concurrency
feng lee
Ā 
KEY
Modern Java Concurrency
Ben Evans
Ā 
PPT
Ā«Š‘Š¾Š»ŃŒŃˆŠøŠµ Š¾Š±ŃŠŃ‘Š¼Ń‹ Ганных Šø сборка Š¼ŃƒŃŠ¾Ń€Š° в Java
Olga Lavrentieva
Ā 
PDF
Clojure concurrency overview
Sergey Stupin
Ā 
PDF
Java synchronizers
ts_v_murthy
Ā 
PDF
[Ruxcon 2011] Post Memory Corruption Memory Analysis
Moabi.com
Ā 
PDF
XS Boston 2008 Paravirt Ops in Linux IA64
The Linux Foundation
Ā 
opt-mem-trx
Miguel Gamboa
Ā 
Twisted
Michal Sedlak
Ā 
Medical Image Processing Strategies for multi-core CPUs
Daniel Blezek
Ā 
Java Runtime: повсеГневные Š¾Š±ŃŠ·Š°Š½Š½Š¾ŃŃ‚Šø JVM
odnoklassniki.ru
Ā 
Java Concurrency in Practice
Alina Dolgikh
Ā 
Scaling Apache Storm - Strata + Hadoop World 2014
P. Taylor Goetz
Ā 
Metasploit Basics
amiable_indian
Ā 
Let's Talk Locks!
C4Media
Ā 
Programming with Threads in Java
koji lin
Ā 
[Blackhat EU'14] Attacking the Linux PRNG on Android and Embedded Devices
srkedmi
Ā 
Nodejs Intro Part One
Budh Ram Gurung
Ā 
Effective java - concurrency
feng lee
Ā 
Modern Java Concurrency
Ben Evans
Ā 
Ā«Š‘Š¾Š»ŃŒŃˆŠøŠµ Š¾Š±ŃŠŃ‘Š¼Ń‹ Ганных Šø сборка Š¼ŃƒŃŠ¾Ń€Š° в Java
Olga Lavrentieva
Ā 
Clojure concurrency overview
Sergey Stupin
Ā 
Java synchronizers
ts_v_murthy
Ā 
[Ruxcon 2011] Post Memory Corruption Memory Analysis
Moabi.com
Ā 
XS Boston 2008 Paravirt Ops in Linux IA64
The Linux Foundation
Ā 
Ad

Recently uploaded (20)

PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
Ā 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
Ā 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
Ā 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
Ā 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
Ā 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
Ā 
PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
Ā 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
Ā 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
Ā 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
Ā 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
Ā 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
Ā 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
Ā 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
Ā 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
Ā 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
Ā 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
Ā 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
Ā 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
Ā 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
Ā 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
Ā 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
Ā 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
Ā 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
Ā 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
Ā 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
Ā 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
Ā 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
Ā 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
Ā 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
Ā 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
Ā 
Kubernetes - Architecture & Components.pdf
geethak285
Ā 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
Ā 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
Ā 
Why aren't you using FME Flow's CPU Time?
Safe Software
Ā 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
Ā 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
Ā 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
Ā 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
Ā 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
Ā 

[JavaOne 2011] Models for Concurrent Programming