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
 
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
Concurrency in Java
Allan Huang
 
KEY
Modern Java Concurrency
Ben Evans
 
DOCX
Java 5 concurrency
priyank09
 
PDF
Java Concurrency Idioms
Alex Miller
 
KEY
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
PDF
Peyton jones-2011-parallel haskell-the_future
Takayuki Muranushi
 
PDF
Simon Peyton Jones: Managing parallelism
Skills Matter
 
PDF
Programming with Threads in Java
koji lin
 
ODP
Concept of thread
Munmun Das Bhowmik
 
ODP
Java Concurrency
Carol McDonald
 
ODP
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
PDF
Java Concurrency in Practice
Alina Dolgikh
 
PPT
Java concurrency
ducquoc_vn
 
PDF
Java synchronizers
ts_v_murthy
 
PPT
Google: Cluster computing and MapReduce: Introduction to Distributed System D...
tugrulh
 
PDF
Concurrency
Phil Steitz
 
PPT
Testing multithreaded java applications for synchronization problems
Vassil Popovski
 
PDF
Concurrency
Isaac Liao
 
PPTX
Retargeting Embedded Software Stack for Many-Core Systems
Sumant Tambe
 
PPTX
Concurrent talk
rahulrevo
 
Concurrency in Java
Allan Huang
 
Modern Java Concurrency
Ben Evans
 
Java 5 concurrency
priyank09
 
Java Concurrency Idioms
Alex Miller
 
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
Peyton jones-2011-parallel haskell-the_future
Takayuki Muranushi
 
Simon Peyton Jones: Managing parallelism
Skills Matter
 
Programming with Threads in Java
koji lin
 
Concept of thread
Munmun Das Bhowmik
 
Java Concurrency
Carol McDonald
 
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Java Concurrency in Practice
Alina Dolgikh
 
Java concurrency
ducquoc_vn
 
Java synchronizers
ts_v_murthy
 
Google: Cluster computing and MapReduce: Introduction to Distributed System D...
tugrulh
 
Concurrency
Phil Steitz
 
Testing multithreaded java applications for synchronization problems
Vassil Popovski
 
Concurrency
Isaac Liao
 
Retargeting Embedded Software Stack for Many-Core Systems
Sumant Tambe
 
Concurrent talk
rahulrevo
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
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
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 

[JavaOne 2011] Models for Concurrent Programming