SlideShare a Scribd company logo
1 of 35
Modern Java
Concurrency


Ben Evans @kittlyst @java7developer

                             Slide Design by Kerry Kenneally www.kerrykenneally.com
Who is this guy anyway?




                          2
Who is this guy anyway?




                          3
Modern Java concurrency

• Not a new subject

• Underwent a revolution with Java 5

• More refinements since (and still more coming in 7)

• j.u.c really fast in 6 (and better yet in 7)

• However, still under-appreciated by a surprising number

• Too much Java 4-style concurrency code still in PROD

• Why...?


                                                            4
Java concurrency - Why not upgrade?
• Too much legacy code - people scared to refactor?

• People don’t know java.util.concurrent is easier
  than “classic” Java concurrency?

• People don’t know j.u.c is faster than classic?

• People don’t know that you can mix-and-match (with a
  bit of care)?

• Still not being taught at Universities?

• Not enough people reading Doug Lea or Brian Goetz?

                                                      5
Modern Java concurrency

• My take: Previous treatments haven’t involved
  enough otters.

• I will rectify this.

• If you suffer from lutraphobia, you may want to leave
  now...




                                                  6
Otterly Amazing Tails of Modern Java
       Concurrency



• Srsly.

• Otters!




                                              7
Why Otters?


• Otters are a very good metaphor
  for concurrency
• Not just because they look a bit
  like threads (ie long and thin)
• Collaborative
• Competitive
• Sneaky
• Can hare off in opposite
  directions
• Capable of wreaking havoc if not
  contained


                                     8
Some History

• Until recently, most computers had only one processing core

• Multithreading was simulated on a single core

• Not true concurrency

• Serial approach to algorithms often sufficed

• Interleaved multithreading can mask errors

• Or be more forgiving than true concurrency

• Why and how (and when) did things change?


                                                         9
Moore’s Law
• “The number of transistors on an economic-to-
  produce chip roughly doubles every 2 years”

• Originally stated in 1965 (and expected to hold for the 10 years to
  1975) - but still going strong

• Named for Gordon Moore (Intel founder)

• About transistor counts

• Not clock speed

• Or overall performance


                                                              10
Transistor Counts




                    11
Moore’s Law - Problems
• Very successful within own frame of reference, but

• Not about overall performance

• Memory latency exponent gap

• Need to keep the processing pipeline full

• Add memory caches of faster SRAM “close” to the CPU (L1, L2
  etc)

• Modern code (after JIT compilation) usually restricted by L1
  processor cache misses rather than CPU speed


                                                            12
Spending the transistor budget




 More and more complex contortions...

 ILP, CMT, Branch prediction, etc, etc

                                         13
Multi-core

• If we can’t increase clock speed / overall perf, have to go multi-
  core

• Concurrency and performance are tied together

• Real concurrency - separate threads can execute on different
  cores at the same moment

• The JVM runtime controls scheduling

• Java thread scheduling does NOT behave like OS scheduling

• Concurrency becomes the main way to squeeze out more
  performance


                                                             14
Classic Concurrency
 synchronized (this) {
    	// do some stuff
 }
• Provides exclusion

• Need locking to make mutation
  concurrency-safe

• Locking gets complicated

• Can become fragile

• Why “synchronized” ?

                                  15
The JMM

• Mathematical
  description of
  memory

• Most impenetrable
  part of the Java
  language spec

• JMM makes            • Primary concepts
                       –   synchronizes-with
  minimum guarantees
                       –   happens-before
                       –   release-before-acquire
• Real JVMs (and
                       –   as-if-serial
  CPUs) may do more
                       • happens-before defines a “partial
                         order” (if you’re a mathematician)

                                                    16
Synchronizes-with

• Threads have their own description of
  an object’s (mutable) state

• Periodically, this must be flushed to
  main memory and other threads

• “synchronized” means that this local
  view has been synchronized-with the
  other threads

• Defines touch-points where threads
  must perform synching

• Compare with NUMA Architectures


                                          17
java.util.concurrent

• Thanks, Doug!

• j.u.c has building blocks for
  concurrent code
    – ReentrantLock
    – Condition
    – ConcurrentHashMap
    – CopyOnWriteArrayList
    – Other Concurrent Data
      Structures



                                  18
Locks and Conditions in j.u.c

  private final Lock lock
= new ReentrantLock();

 lock.lock();

 try {
                             • Lock is an interface
  	 // do some stuff
 } finally {                 • ReentrantLock is usual
    lock.unlock();             implementation
 }
                             • Condition takes the place
                               of wait() / notify()

                                                19
ConcurrentHashMap

• HashMap has:
   – Hash function
   – Even distribution of buckets

• Concurrent form
   – Can lock independently
   – Seems lock-free to users
   – Has atomic operations

• Basically drop-in replacement



                                    20
CopyOnWriteArrayList

• Similar to CHM

• Not quite a drop-in replacement

• Iterator will never throw
  ConcurrentModificationException

• Makes separate copies of underlying
  structure




                                        21
CountDownLatch

•   A group consensus construct

•   2 methods - countDown() and
    await()
     – countDown() decrements the
       count
     – await() blocks until the count
       reaches zero (i.e. consensus)

•   Ctor takes an int param - the count

•   Quite a few use cases

•   Especially multithreaded testing


                                          22
Handoff Queue (in-mem)
•   Efficient way to hand off work between threads
    (or threadpools)

•   BlockingQueue is often a good choice

•   Offers several different ways to interact with it
    (see Javadoc)

•   Blocking operations with timeouts can be very
    useful (eg for backoff / retry)

•   Two basic impls - ArrayList and
    LinkedList backed

•   Java 7 introduces the shiny new
    TransferQueue


                                                        23
Executors
•   j.u.c execution constructs - Callable,
    Future, FutureTask

•   In addition to the venerable Thread and
    Runnable

•   Stop using TimerTask!

•   The Executors class provides lots of helpful
    factory methods for making threadpools

•   ScheduledThreadPoolExecutor is one
    standard choice (but there are others)

•   The final building block for making modern
    concurrent applications


                                                   24
Example - ThreadPoolManager
private final ScheduledExecutorService stpe =
Executors.newScheduledThreadPool(2);


private final BlockingQueue<WorkUnit<String>> lbq;


public ScheduledFuture<?> run(QueueReaderTask msgReader) {
  msgReader.setQueue(lbq);
  return stpe.scheduleAtFixedRate(msgReader, 10, 10,
TimeUnit.MILLISECONDS);
}


public void cancel(final ScheduledFuture<?> handle) {
  stpe.schedule(new Runnable() {
    public void run() { handle.cancel(true); }
  }, 10, TimeUnit.MILLISECONDS);
}



                                                             25
                                                             23
Example - QueueReaderTask
public abstract class QueueReaderTask implements Runnable {
    private boolean shutdown = false;
    protected BlockingQueue<WorkUnit<String>> lbq;


    public void run() {
        while (!shutdown) {
            try {
                WorkUnit<String> wu = lbq.poll(10, TimeUnit.MILLISECONDS);
                if (wu != null) doAction(wu.getWork());
            } catch (InterruptedException e) {
                shutdown = true;
            }
        }
    }
    public abstract void doAction(String msg);
    public void setQueue(BlockingQueue<WorkUnit<String>> q) { lbq = q; }
}

                                                                     26
                                                                     23
Fork/Join

• Java 7 introduces F/J
   – similar to MapReduce
   – useful for a certain class of problems
   – F/J executions are not really threads

• In our example, we subclass RecursiveAction


• Need to provide a compute() method and a way of merging
  results

• Framework provides an invokeAll() to hand off more tasks




                                                       27
                                                       28
Fork/Join

@Override
protected void compute() {
  if (size() < SMALL_ENOUGH) {
    System.arraycopy(updates, start, result, 0, size());
    Arrays.sort(result, 0, size());
  } else {
    int mid = size() / 2;
    BlogSorter left = new BlogSorter(updates, start, start + mid);
    BlogSorter right = new BlogSorter(updates, start + mid, end);

        invokeAll(left, right);
        merge(left, right);
    }
}




                                                            28
                                                            29
Fork/Join
private void merge(BlogSorter left, BlogSorter right) {
  int i = 0;
  int lCt = 0;
  int rCt = 0;

    while (lCt < left.size() && rCt < right.size()) {
      result[i++] = (left.result[lCt].compareTo(right.result[rCt]) < 0)
           ? left.result[lCt++]
           : right.result[rCt++];
    }
    while (lCt < left.size()) result[i++] = left.result[lCt++];
    while (rCt < right.size()) result[i++] = right.result[rCt++];
}


public int size() { return end - start; }
public Update[] getResult() { return result; }



                                                              29
                                                              30
Concurrent Java Code

• Mutable state (objects) protected by locks

• Concurrent data structures (CHM, COWAL)

• Be careful of performance (esp COWAL)

• Synchronous multithreading - explicit synchronization

• Executor-based threadpools

• Asynch multithreading communicates using queue-like handoffs




                                                          30
Stepping Back

• Concurrency is key to the future of
  performant code

• Mutable state is hard

• Need both synch & asynch state sharing

• Locks can be hard to use correctly

• JMM is a low-level, flexible model
    – Need higher-level concurrency model
    – Thread is still too low-level



                                            31
Imagine a world...
• Collections were thread-safe by default

• Objects were immutable by default

• State was well encapsulated and not shared by default

• The runtime helped out the programmer more

• Thread wasn’t the default choice for unit of concurrent execution

• Copy-on-write was the basis for mutation of collections /
  synchronous multithreading

• Hand-off (via something queue-like) was the basis for asynchronous
  multithreading
                                                              32
Wouldn’t it be nice?
• Imagine all of that was built-in to the language syntax

• But still built on top of the JVM

• Still based on the JMM view of memory

• What could such a language be?

• One thing’s for sure - it’s not Java

• We can’t fix Java now, but we can learn from it (both
  good and bad points

• And we can dream...

                                                            33
Acknowledgments


• All otter images Creative Commons or Fair Use

• Photos owned by Flickr Users: moff, spark, sodaro,
  lonecellotheory, tomsowerby, farnsworth, prince,
  marcus_jb1973, mliu92, Ed Zitron, NaturalLight &
  monkeywing

• Dancing Otter by the amazing Nicola Slater @ folksy




                                                  34
Thank You http://www.java7developer.com/




                                   35

More Related Content

What's hot

Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Sachintha Gunasena
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Roman Elizarov
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?Roman Elizarov
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsAnton Keks
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingRobert Brown
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924yohanbeschi
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsKwangshin Oh
 

What's hot (20)

Java memory model
Java memory modelJava memory model
Java memory model
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
 

Similar to Modern Java Concurrency

Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Martijn Verburg
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Martijn Verburg
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfjexp
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
New hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfNew hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfKrystian Zybała
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9Gal Marder
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance TuningJeremy Leisy
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Mike Slinn
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Martijn Verburg
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threadsSyed Zaid Irshad
 
Parallel programming
Parallel programmingParallel programming
Parallel programmingSwain Loda
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 

Similar to Modern Java Concurrency (20)

Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdf
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
New hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfNew hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdf
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Threads
ThreadsThreads
Threads
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
 
Parallel programming
Parallel programmingParallel programming
Parallel programming
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 

Recently uploaded

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Recently uploaded (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

Modern Java Concurrency

  • 1. Modern Java Concurrency Ben Evans @kittlyst @java7developer Slide Design by Kerry Kenneally www.kerrykenneally.com
  • 2. Who is this guy anyway? 2
  • 3. Who is this guy anyway? 3
  • 4. Modern Java concurrency • Not a new subject • Underwent a revolution with Java 5 • More refinements since (and still more coming in 7) • j.u.c really fast in 6 (and better yet in 7) • However, still under-appreciated by a surprising number • Too much Java 4-style concurrency code still in PROD • Why...? 4
  • 5. Java concurrency - Why not upgrade? • Too much legacy code - people scared to refactor? • People don’t know java.util.concurrent is easier than “classic” Java concurrency? • People don’t know j.u.c is faster than classic? • People don’t know that you can mix-and-match (with a bit of care)? • Still not being taught at Universities? • Not enough people reading Doug Lea or Brian Goetz? 5
  • 6. Modern Java concurrency • My take: Previous treatments haven’t involved enough otters. • I will rectify this. • If you suffer from lutraphobia, you may want to leave now... 6
  • 7. Otterly Amazing Tails of Modern Java Concurrency • Srsly. • Otters! 7
  • 8. Why Otters? • Otters are a very good metaphor for concurrency • Not just because they look a bit like threads (ie long and thin) • Collaborative • Competitive • Sneaky • Can hare off in opposite directions • Capable of wreaking havoc if not contained 8
  • 9. Some History • Until recently, most computers had only one processing core • Multithreading was simulated on a single core • Not true concurrency • Serial approach to algorithms often sufficed • Interleaved multithreading can mask errors • Or be more forgiving than true concurrency • Why and how (and when) did things change? 9
  • 10. Moore’s Law • “The number of transistors on an economic-to- produce chip roughly doubles every 2 years” • Originally stated in 1965 (and expected to hold for the 10 years to 1975) - but still going strong • Named for Gordon Moore (Intel founder) • About transistor counts • Not clock speed • Or overall performance 10
  • 12. Moore’s Law - Problems • Very successful within own frame of reference, but • Not about overall performance • Memory latency exponent gap • Need to keep the processing pipeline full • Add memory caches of faster SRAM “close” to the CPU (L1, L2 etc) • Modern code (after JIT compilation) usually restricted by L1 processor cache misses rather than CPU speed 12
  • 13. Spending the transistor budget More and more complex contortions... ILP, CMT, Branch prediction, etc, etc 13
  • 14. Multi-core • If we can’t increase clock speed / overall perf, have to go multi- core • Concurrency and performance are tied together • Real concurrency - separate threads can execute on different cores at the same moment • The JVM runtime controls scheduling • Java thread scheduling does NOT behave like OS scheduling • Concurrency becomes the main way to squeeze out more performance 14
  • 15. Classic Concurrency synchronized (this) { // do some stuff } • Provides exclusion • Need locking to make mutation concurrency-safe • Locking gets complicated • Can become fragile • Why “synchronized” ? 15
  • 16. The JMM • Mathematical description of memory • Most impenetrable part of the Java language spec • JMM makes • Primary concepts – synchronizes-with minimum guarantees – happens-before – release-before-acquire • Real JVMs (and – as-if-serial CPUs) may do more • happens-before defines a “partial order” (if you’re a mathematician) 16
  • 17. Synchronizes-with • Threads have their own description of an object’s (mutable) state • Periodically, this must be flushed to main memory and other threads • “synchronized” means that this local view has been synchronized-with the other threads • Defines touch-points where threads must perform synching • Compare with NUMA Architectures 17
  • 18. java.util.concurrent • Thanks, Doug! • j.u.c has building blocks for concurrent code – ReentrantLock – Condition – ConcurrentHashMap – CopyOnWriteArrayList – Other Concurrent Data Structures 18
  • 19. Locks and Conditions in j.u.c private final Lock lock = new ReentrantLock(); lock.lock(); try { • Lock is an interface // do some stuff } finally { • ReentrantLock is usual lock.unlock(); implementation } • Condition takes the place of wait() / notify() 19
  • 20. ConcurrentHashMap • HashMap has: – Hash function – Even distribution of buckets • Concurrent form – Can lock independently – Seems lock-free to users – Has atomic operations • Basically drop-in replacement 20
  • 21. CopyOnWriteArrayList • Similar to CHM • Not quite a drop-in replacement • Iterator will never throw ConcurrentModificationException • Makes separate copies of underlying structure 21
  • 22. CountDownLatch • A group consensus construct • 2 methods - countDown() and await() – countDown() decrements the count – await() blocks until the count reaches zero (i.e. consensus) • Ctor takes an int param - the count • Quite a few use cases • Especially multithreaded testing 22
  • 23. Handoff Queue (in-mem) • Efficient way to hand off work between threads (or threadpools) • BlockingQueue is often a good choice • Offers several different ways to interact with it (see Javadoc) • Blocking operations with timeouts can be very useful (eg for backoff / retry) • Two basic impls - ArrayList and LinkedList backed • Java 7 introduces the shiny new TransferQueue 23
  • 24. Executors • j.u.c execution constructs - Callable, Future, FutureTask • In addition to the venerable Thread and Runnable • Stop using TimerTask! • The Executors class provides lots of helpful factory methods for making threadpools • ScheduledThreadPoolExecutor is one standard choice (but there are others) • The final building block for making modern concurrent applications 24
  • 25. Example - ThreadPoolManager private final ScheduledExecutorService stpe = Executors.newScheduledThreadPool(2); private final BlockingQueue<WorkUnit<String>> lbq; public ScheduledFuture<?> run(QueueReaderTask msgReader) { msgReader.setQueue(lbq); return stpe.scheduleAtFixedRate(msgReader, 10, 10, TimeUnit.MILLISECONDS); } public void cancel(final ScheduledFuture<?> handle) { stpe.schedule(new Runnable() { public void run() { handle.cancel(true); } }, 10, TimeUnit.MILLISECONDS); } 25 23
  • 26. Example - QueueReaderTask public abstract class QueueReaderTask implements Runnable { private boolean shutdown = false; protected BlockingQueue<WorkUnit<String>> lbq; public void run() { while (!shutdown) { try { WorkUnit<String> wu = lbq.poll(10, TimeUnit.MILLISECONDS); if (wu != null) doAction(wu.getWork()); } catch (InterruptedException e) { shutdown = true; } } } public abstract void doAction(String msg); public void setQueue(BlockingQueue<WorkUnit<String>> q) { lbq = q; } } 26 23
  • 27. Fork/Join • Java 7 introduces F/J – similar to MapReduce – useful for a certain class of problems – F/J executions are not really threads • In our example, we subclass RecursiveAction • Need to provide a compute() method and a way of merging results • Framework provides an invokeAll() to hand off more tasks 27 28
  • 28. Fork/Join @Override protected void compute() { if (size() < SMALL_ENOUGH) { System.arraycopy(updates, start, result, 0, size()); Arrays.sort(result, 0, size()); } else { int mid = size() / 2; BlogSorter left = new BlogSorter(updates, start, start + mid); BlogSorter right = new BlogSorter(updates, start + mid, end); invokeAll(left, right); merge(left, right); } } 28 29
  • 29. Fork/Join private void merge(BlogSorter left, BlogSorter right) { int i = 0; int lCt = 0; int rCt = 0; while (lCt < left.size() && rCt < right.size()) { result[i++] = (left.result[lCt].compareTo(right.result[rCt]) < 0) ? left.result[lCt++] : right.result[rCt++]; } while (lCt < left.size()) result[i++] = left.result[lCt++]; while (rCt < right.size()) result[i++] = right.result[rCt++]; } public int size() { return end - start; } public Update[] getResult() { return result; } 29 30
  • 30. Concurrent Java Code • Mutable state (objects) protected by locks • Concurrent data structures (CHM, COWAL) • Be careful of performance (esp COWAL) • Synchronous multithreading - explicit synchronization • Executor-based threadpools • Asynch multithreading communicates using queue-like handoffs 30
  • 31. Stepping Back • Concurrency is key to the future of performant code • Mutable state is hard • Need both synch & asynch state sharing • Locks can be hard to use correctly • JMM is a low-level, flexible model – Need higher-level concurrency model – Thread is still too low-level 31
  • 32. Imagine a world... • Collections were thread-safe by default • Objects were immutable by default • State was well encapsulated and not shared by default • The runtime helped out the programmer more • Thread wasn’t the default choice for unit of concurrent execution • Copy-on-write was the basis for mutation of collections / synchronous multithreading • Hand-off (via something queue-like) was the basis for asynchronous multithreading 32
  • 33. Wouldn’t it be nice? • Imagine all of that was built-in to the language syntax • But still built on top of the JVM • Still based on the JMM view of memory • What could such a language be? • One thing’s for sure - it’s not Java • We can’t fix Java now, but we can learn from it (both good and bad points • And we can dream... 33
  • 34. Acknowledgments • All otter images Creative Commons or Fair Use • Photos owned by Flickr Users: moff, spark, sodaro, lonecellotheory, tomsowerby, farnsworth, prince, marcus_jb1973, mliu92, Ed Zitron, NaturalLight & monkeywing • Dancing Otter by the amazing Nicola Slater @ folksy 34

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. * Everyone hands up (&amp; repeat)\n* OK, put your hand down if the primary VM you use at work is version 5 or lower\n* Version 4?\n
  5. * Hands up if you&amp;#x2019;re daunted by the refactoring that would be required\n\n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. * It&amp;#x2019;s a little-known fact that Otters are scared of log-linear graphs\n
  12. \n
  13. * So you can contort more and more, but you&amp;#x2019;re chasing diminishing returns\n* Ultimately, that exponent gap between clock speed and memory will do for you\n
  14. * Raise your hand if you use the process monitor on Ubuntu or another Linux. OK, have you seen how Java processes behave under that?\n
  15. * Raise your hand if you know why we use the keyword &amp;#x201C;synchronized&amp;#x201D; to denote a critical section in Java\n
  16. \n
  17. * Hands up if you know what a NUMA architecture is?\n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. * Let&amp;#x2019;s step through a quasi-realistic example\n
  26. \n
  27. \n
  28. \n
  29. \n
  30. * So this is pretty much a statement of the state-of-the-art in Java concurrency\n
  31. * But let&amp;#x2019;s step back - and talk about concurrency in general, rather than just in the context of Java\n
  32. \n
  33. \n
  34. \n
  35. \n