SlideShare una empresa de Scribd logo
1 de 47
Descargar para leer sin conexión
The WGJD - Modern Java
     Concurrency
    Ben Evans and Martijn Verburg
       (@kittylyst @karianna)

        http://www.teamsparq.net


    Slide Design by http://www.kerrykenneally.com
Are you a fluffy animal lover..?
         Leave now.



                              2
Why Modern Java Concurrency is important


• The WGJD wants to utilise modern hardware

• The WGJD wants to write concurrent code
   – Safely
   – Without fear
   – With an understanding of performance implications


• The WGJD wants to take advantage of:
   – JVM support for parallelised operations
   – An API that avoids synchronized


• Modern Java Concurrency lets you do all of this



                                                         3
About this section


• We only have ~60mins hour to talk today

• Huge amount to talk about

• This subject fills 2 (or even 4) days worth of training

• We will give you some highlights today

• For die-hard low latency fiends
   – Locks are actually bad OK!
   – Come talk to us afterwards to find out more




                                                            4
Modern Java concurrency


• Not a new subject
   – Underwent a revolution with Java 5


• More refinements since
   – Still more coming in 7


• java.util.concurrent (j.u.c) really fast in 6
   – Better yet in 7


• However, still under-appreciated by a surprising number

• Too much Java 4-style concurrency code still in PROD
   – Why...?

                                                            5
Java concurrency - Why not upgrade?


• Too much legacy code?
   – People scared to refactor?


• People don’t know j.u.c 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?


                                                             6
Modern Java concurrency


• Perhaps........
   – Previous treatments haven’t involved enough otters.


• We will rectify this.

• If you suffer from lutraphobia, you may want to leave now...
   – We did warn you about fluffy animals
   – Ones that BITE




                                                                 7
Otterly Amazing Tails of Modern Java
           Concurrency

• Srsly.

• Otters!

• See those
  teeth?




                                                  8
Why Otters?


• Otters are a very good metaphor
  for concurrency

• Not just because they look a bit
  like threads (i.e. long and thin)

• Collaborative, Competitive & Sneaky

• Can hare off in opposite directions

• Capable of wreaking havoc
  if not contained


                                        9
Otter Management (aka the 4 forces)


• Safety
   – Does each object stay self-consistent?
   – No matter what other operations are happening?


• Liveness
   – Does the program eventually progress?
   – Are any failures to progress temporary or permanent?


• Performance
   – How well does the system take advantage of processing cores?


• Reusability
   – How easy is it to reuse the system in other applications?

                                                                 10
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?




                                                            11
Moore’s Law


• “The number of transistors on an economic-to-produce chip roughly
  doubles every 2 years”

• Originally stated in 1965
   – Expected to hold for the 10 years to 1975
   – Still going strong


• Named for Gordon Moore (Intel founder)
   – About transistor counts
   – Not clock speed
   – Or overall performance




                                                           12
Transistor Counts




                    13
Moore’s Law - Problems


• 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)


• Code restricted by L1 cache misses rather than CPU speed
   – After JIT compilation




                                                           14
Spending the transistor budget




• More and more complex contortions...

• ILP, CMT, Branch prediction, etc, etc
                                          15
Multi-core


• If we can’t increase clock speed / overall performance
   – Have to go multi-core
   – Concurrency and performance are tied together


• Real concurrency
   – Separate threads executing on different cores at the same moment


• The JVM runtime controls scheduling
   – Java thread scheduling does NOT behave like OS scheduling


• Concurrency becomes the performance improver




                                                                 16
Classic Java Concurrency


• Provides exclusion




• Need locking to make
  mutation concurrency-safe

• Locking gets complicated

• Can become fragile

• Why synchronized?


                                   17
I wrap sychronized....
 around entire classes


  Safe as Fort Knox
                         18
Three approaches to Concurrent Type Safety


• Fully-synchronized Objects
   – Synchronize all methods on all classes


• Immutability
   – Useful, but may have high copy-cost
   – Requires programmer discipline


• Be Very, Very Careful
   – Difficult
   – Fragile
   – With Java - Often the only game in town




                                               19
The JMM


• Mathematical
  description of memory

• Most impenetrable
  part of the Java
  language spec

• JMM makes               Primary concepts:
  minimum guarantees        • synchronizes-with
                            • happens-before
• Real JVMs (and CPUs)      • release-before-acquire
  may do more               • as-if-serial

                                                  20
Synchronizes-with


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

• 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



                                                             21
java.util.concurrent


• Thanks, Doug!

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




                                          22
Locks in j.u.c




• Lock is an interface


• ReentrantLock is the usual implementation



                                              23
I always wanted
 to be an actor



                  24
Conditions in j.u.c




                      25
Conditions in j.u.c




                      26
ConcurrentHashMap (CHM)


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


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




                                    27
CopyOnWriteArrayList (COWAL)



• Makes separate copies of
  underlying structure

• Iterator will never throw
  ConcurrentModificationException




                                       28
CountDownLatch


• A group consensus construct

• countDown() decrements
  the count

• await() blocks until
  count == 0
   – i.e. consensus


• Constructor takes an int (the count)

• Quite a few use cases
   – e.g. Multithreaded testing
                                         29
Example - CountDownLatch




                           30
Handoff Queue (in-mem)


• Efficient way to hand off work
  between threadpools

• BlockingQueue a good pick

• Has blocking ops with timeouts
   – e.g. for backoff / retry


• Two basic implementations
   – ArrayList and LinkedList backed


• Java 7 introduces the shiny new TransferQueue


                                                  31
Just use JMS!




                32
Example - LinkedBlockingQueue




• Imagine multiple producers and consumers
                                             33
Executors


• j.u.c execution constructs
   – Callable, Future,
     FutureTask


• In addition to the venerable
   – Thread and Runnable


• Stop using TimerTask!


• Executors class provides factory methods for making threadpools
   – ScheduledThreadPoolExecutor is one standard choice




                                                          34
Animals were harmed in the
 making of this presentation


    Crab got executed

                           35
Example - ThreadPoolManager




                              36
Example - QueueReaderTask




                            37
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


• F/J provides an invokeAll() to hand off more tasks


                                                       38
Fork/Join




• Typical divide and conquer style problem
   – invokeall() performs the threadpool, worker & queue magic


                                                             39
Concurrent Java Code


• Mutable state (objects) protected by locks

• Concurrent data structures
   – CHM, COWAL


• Be careful of performance
   – especially COWAL


• Synchronous multithreading - explicit synchronization

• Executor-based threadpools

• Asynch multithreading communicates using queue-like handoffs

                                                          40
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


                                           41
Imagine a world...


• The runtime & environment helped out the programmer more:
   –   Runtime-managed concurrency
   –   Collections were thread-safe by default
   –   Objects were immutable by default
   –   State was well encapsulated and not shared by default


• 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 queues were the basis for asynchronous multithreading



                                                               42
What can we do with Java?


• We’re stuck with a lot of heritage in Java
   – But the JVM and JMM are very sound


• You don’t have to abandon Java
   – Mechanical sympathy and clean code get you far
   – The JIT compiler just gets better and better


• If we wanted to dream of a new language
   – It should be on the JVM
   – It should build on what we’ve learned in 15 years of Java




                                                                 43
New Frontiers in Concurrency


• There are several options now on the JVM
   – New possibilities built-in to the language syntax
   – Synch and asynch models


• Scala offers an Actors model
   – And the powerful Akka framework

• Clojure is immutable by default
   – Has agents (like actors) & shared-nothing by default
   – Also has a Software Transactional Memory (STM) model

• Groovy has GPARs



                                                            44
Acknowledgments


• All otter images Creative Commons or Fair Use

• Matt Raible

• Ola Bini

• 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


                                                             45
Where is our beer!?




                      46
Thanks for listening! (@kittylyst, @karianna)




• http://www.teamsparq.net
• http://www.java7developer.com                  47

Más contenido relacionado

La actualidad más candente

Over 9000: JRuby in 2015
Over 9000: JRuby in 2015Over 9000: JRuby in 2015
Over 9000: JRuby in 2015Charles Nutter
 
Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08Benoit Perroud
 
Pregel: A System for Large-Scale Graph Processing
Pregel: A System for Large-Scale Graph ProcessingPregel: A System for Large-Scale Graph Processing
Pregel: A System for Large-Scale Graph ProcessingChris Bunch
 
Concurrency vs parallelism
Concurrency vs parallelismConcurrency vs parallelism
Concurrency vs parallelismYiwei Gong
 
Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...
Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...
Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...srisatish ambati
 
Verification with LoLA: 4 Using LoLA
Verification with LoLA: 4 Using LoLAVerification with LoLA: 4 Using LoLA
Verification with LoLA: 4 Using LoLAUniversität Rostock
 
Yet Another Replication Tool: RubyRep
Yet Another Replication Tool: RubyRepYet Another Replication Tool: RubyRep
Yet Another Replication Tool: RubyRepDenish Patel
 
Cooking a rabbit pie
Cooking a rabbit pieCooking a rabbit pie
Cooking a rabbit pieTomas Doran
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript ProgrammingYoshiki Shibukawa
 

La actualidad más candente (10)

Over 9000: JRuby in 2015
Over 9000: JRuby in 2015Over 9000: JRuby in 2015
Over 9000: JRuby in 2015
 
Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08Direct memory jugl-2012.03.08
Direct memory jugl-2012.03.08
 
Pregel: A System for Large-Scale Graph Processing
Pregel: A System for Large-Scale Graph ProcessingPregel: A System for Large-Scale Graph Processing
Pregel: A System for Large-Scale Graph Processing
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Concurrency vs parallelism
Concurrency vs parallelismConcurrency vs parallelism
Concurrency vs parallelism
 
Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...
Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...
Cache is King ( Or How To Stop Worrying And Start Caching in Java) at Chicago...
 
Verification with LoLA: 4 Using LoLA
Verification with LoLA: 4 Using LoLAVerification with LoLA: 4 Using LoLA
Verification with LoLA: 4 Using LoLA
 
Yet Another Replication Tool: RubyRep
Yet Another Replication Tool: RubyRepYet Another Replication Tool: RubyRep
Yet Another Replication Tool: RubyRep
 
Cooking a rabbit pie
Cooking a rabbit pieCooking a rabbit pie
Cooking a rabbit pie
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript Programming
 

Destacado

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
 
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)Martijn Verburg
 
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)Martijn Verburg
 
Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)Martijn Verburg
 
Free community with deep roots
Free community with deep rootsFree community with deep roots
Free community with deep rootsMartijn Verburg
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Martijn Verburg
 
Introduction to Java 7 (Devoxx Nov/2011)
Introduction to Java 7 (Devoxx Nov/2011)Introduction to Java 7 (Devoxx Nov/2011)
Introduction to Java 7 (Devoxx Nov/2011)Martijn Verburg
 
Garbage Collection - The Useful Parts
Garbage Collection - The Useful PartsGarbage Collection - The Useful Parts
Garbage Collection - The Useful PartsMartijn Verburg
 
Modern software development anti patterns (OSCON 2012)
Modern software development anti patterns (OSCON 2012)Modern software development anti patterns (OSCON 2012)
Modern software development anti patterns (OSCON 2012)Martijn Verburg
 

Destacado (10)

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)
 
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
Adopt OpenJDK - Lessons learned and Where we're going (FOSDEM 2013)
 
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
Paperwork, Politics and Pain - Our year in the JCP (FOSDEM 2012)
 
Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)Introduction to Java 7 (OSCON 2012)
Introduction to Java 7 (OSCON 2012)
 
Free community with deep roots
Free community with deep rootsFree community with deep roots
Free community with deep roots
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 
Introduction to Java 7 (Devoxx Nov/2011)
Introduction to Java 7 (Devoxx Nov/2011)Introduction to Java 7 (Devoxx Nov/2011)
Introduction to Java 7 (Devoxx Nov/2011)
 
NoHR Hiring
NoHR HiringNoHR Hiring
NoHR Hiring
 
Garbage Collection - The Useful Parts
Garbage Collection - The Useful PartsGarbage Collection - The Useful Parts
Garbage Collection - The Useful Parts
 
Modern software development anti patterns (OSCON 2012)
Modern software development anti patterns (OSCON 2012)Modern software development anti patterns (OSCON 2012)
Modern software development anti patterns (OSCON 2012)
 

Similar a Modern Java Concurrency Highlights

Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
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
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel ProgrammingUday Sharma
 
Java in High Frequency Trading
Java in High Frequency TradingJava in High Frequency Trading
Java in High Frequency TradingViktor Sovietov
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Mike Slinn
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaLakshmi Narasimhan
 
Writing Scalable Software in Java
Writing Scalable Software in JavaWriting Scalable Software in Java
Writing Scalable Software in JavaRuben Badaró
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threadsmperham
 
LMAX Disruptor - High Performance Inter-Thread Messaging Library
LMAX Disruptor - High Performance Inter-Thread Messaging LibraryLMAX Disruptor - High Performance Inter-Thread Messaging Library
LMAX Disruptor - High Performance Inter-Thread Messaging LibrarySebastian Andrasoni
 
Scalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsJonas Bonér
 
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...InfinIT - Innovationsnetværket for it
 
High Scalability Toronto: Meetup #2
High Scalability Toronto: Meetup #2High Scalability Toronto: Meetup #2
High Scalability Toronto: Meetup #2ScribbleLive
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQLDon Demcsak
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9Gal Marder
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Charles Nutter
 

Similar a Modern Java Concurrency Highlights (20)

Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
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
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Java in High Frequency Trading
Java in High Frequency TradingJava in High Frequency Trading
Java in High Frequency Trading
 
Composable Futures with Akka 2.0
Composable Futures with Akka 2.0Composable Futures with Akka 2.0
Composable Futures with Akka 2.0
 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Writing Scalable Software in Java
Writing Scalable Software in JavaWriting Scalable Software in Java
Writing Scalable Software in Java
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
LMAX Disruptor - High Performance Inter-Thread Messaging Library
LMAX Disruptor - High Performance Inter-Thread Messaging LibraryLMAX Disruptor - High Performance Inter-Thread Messaging Library
LMAX Disruptor - High Performance Inter-Thread Messaging Library
 
Scalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability Patterns
 
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
 
High Scalability Toronto: Meetup #2
High Scalability Toronto: Meetup #2High Scalability Toronto: Meetup #2
High Scalability Toronto: Meetup #2
 
Lect06
Lect06Lect06
Lect06
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQL
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014
 
CPU Caches
CPU CachesCPU Caches
CPU Caches
 
JavaFX 101
JavaFX 101JavaFX 101
JavaFX 101
 

Último

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
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
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 

Último (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
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
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 

Modern Java Concurrency Highlights

  • 1. The WGJD - Modern Java Concurrency Ben Evans and Martijn Verburg (@kittylyst @karianna) http://www.teamsparq.net Slide Design by http://www.kerrykenneally.com
  • 2. Are you a fluffy animal lover..? Leave now. 2
  • 3. Why Modern Java Concurrency is important • The WGJD wants to utilise modern hardware • The WGJD wants to write concurrent code – Safely – Without fear – With an understanding of performance implications • The WGJD wants to take advantage of: – JVM support for parallelised operations – An API that avoids synchronized • Modern Java Concurrency lets you do all of this 3
  • 4. About this section • We only have ~60mins hour to talk today • Huge amount to talk about • This subject fills 2 (or even 4) days worth of training • We will give you some highlights today • For die-hard low latency fiends – Locks are actually bad OK! – Come talk to us afterwards to find out more 4
  • 5. Modern Java concurrency • Not a new subject – Underwent a revolution with Java 5 • More refinements since – Still more coming in 7 • java.util.concurrent (j.u.c) really fast in 6 – Better yet in 7 • However, still under-appreciated by a surprising number • Too much Java 4-style concurrency code still in PROD – Why...? 5
  • 6. Java concurrency - Why not upgrade? • Too much legacy code? – People scared to refactor? • People don’t know j.u.c 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? 6
  • 7. Modern Java concurrency • Perhaps........ – Previous treatments haven’t involved enough otters. • We will rectify this. • If you suffer from lutraphobia, you may want to leave now... – We did warn you about fluffy animals – Ones that BITE 7
  • 8. Otterly Amazing Tails of Modern Java Concurrency • Srsly. • Otters! • See those teeth? 8
  • 9. Why Otters? • Otters are a very good metaphor for concurrency • Not just because they look a bit like threads (i.e. long and thin) • Collaborative, Competitive & Sneaky • Can hare off in opposite directions • Capable of wreaking havoc if not contained 9
  • 10. Otter Management (aka the 4 forces) • Safety – Does each object stay self-consistent? – No matter what other operations are happening? • Liveness – Does the program eventually progress? – Are any failures to progress temporary or permanent? • Performance – How well does the system take advantage of processing cores? • Reusability – How easy is it to reuse the system in other applications? 10
  • 11. 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? 11
  • 12. Moore’s Law • “The number of transistors on an economic-to-produce chip roughly doubles every 2 years” • Originally stated in 1965 – Expected to hold for the 10 years to 1975 – Still going strong • Named for Gordon Moore (Intel founder) – About transistor counts – Not clock speed – Or overall performance 12
  • 14. Moore’s Law - Problems • 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) • Code restricted by L1 cache misses rather than CPU speed – After JIT compilation 14
  • 15. Spending the transistor budget • More and more complex contortions... • ILP, CMT, Branch prediction, etc, etc 15
  • 16. Multi-core • If we can’t increase clock speed / overall performance – Have to go multi-core – Concurrency and performance are tied together • Real concurrency – Separate threads executing on different cores at the same moment • The JVM runtime controls scheduling – Java thread scheduling does NOT behave like OS scheduling • Concurrency becomes the performance improver 16
  • 17. Classic Java Concurrency • Provides exclusion • Need locking to make mutation concurrency-safe • Locking gets complicated • Can become fragile • Why synchronized? 17
  • 18. I wrap sychronized.... around entire classes Safe as Fort Knox 18
  • 19. Three approaches to Concurrent Type Safety • Fully-synchronized Objects – Synchronize all methods on all classes • Immutability – Useful, but may have high copy-cost – Requires programmer discipline • Be Very, Very Careful – Difficult – Fragile – With Java - Often the only game in town 19
  • 20. The JMM • Mathematical description of memory • Most impenetrable part of the Java language spec • JMM makes Primary concepts: minimum guarantees • synchronizes-with • happens-before • Real JVMs (and CPUs) • release-before-acquire may do more • as-if-serial 20
  • 21. Synchronizes-with • Threads have their own description of an object’s state • 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 21
  • 22. java.util.concurrent • Thanks, Doug! • j.u.c has building blocks for concurrent code – ReentrantLock – Condition – ConcurrentHashMap – CopyOnWriteArrayList – Other Concurrent Data Structures 22
  • 23. Locks in j.u.c • Lock is an interface • ReentrantLock is the usual implementation 23
  • 24. I always wanted to be an actor 24
  • 27. ConcurrentHashMap (CHM) • HashMap has: – Hash function – Even distribution of buckets • Concurrent form – Can lock independently – Seems lock-free to users – Has atomic operations 27
  • 28. CopyOnWriteArrayList (COWAL) • Makes separate copies of underlying structure • Iterator will never throw ConcurrentModificationException 28
  • 29. CountDownLatch • A group consensus construct • countDown() decrements the count • await() blocks until count == 0 – i.e. consensus • Constructor takes an int (the count) • Quite a few use cases – e.g. Multithreaded testing 29
  • 31. Handoff Queue (in-mem) • Efficient way to hand off work between threadpools • BlockingQueue a good pick • Has blocking ops with timeouts – e.g. for backoff / retry • Two basic implementations – ArrayList and LinkedList backed • Java 7 introduces the shiny new TransferQueue 31
  • 33. Example - LinkedBlockingQueue • Imagine multiple producers and consumers 33
  • 34. Executors • j.u.c execution constructs – Callable, Future, FutureTask • In addition to the venerable – Thread and Runnable • Stop using TimerTask! • Executors class provides factory methods for making threadpools – ScheduledThreadPoolExecutor is one standard choice 34
  • 35. Animals were harmed in the making of this presentation Crab got executed 35
  • 38. 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 • F/J provides an invokeAll() to hand off more tasks 38
  • 39. Fork/Join • Typical divide and conquer style problem – invokeall() performs the threadpool, worker & queue magic 39
  • 40. Concurrent Java Code • Mutable state (objects) protected by locks • Concurrent data structures – CHM, COWAL • Be careful of performance – especially COWAL • Synchronous multithreading - explicit synchronization • Executor-based threadpools • Asynch multithreading communicates using queue-like handoffs 40
  • 41. 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 41
  • 42. Imagine a world... • The runtime & environment helped out the programmer more: – Runtime-managed concurrency – Collections were thread-safe by default – Objects were immutable by default – State was well encapsulated and not shared by default • 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 queues were the basis for asynchronous multithreading 42
  • 43. What can we do with Java? • We’re stuck with a lot of heritage in Java – But the JVM and JMM are very sound • You don’t have to abandon Java – Mechanical sympathy and clean code get you far – The JIT compiler just gets better and better • If we wanted to dream of a new language – It should be on the JVM – It should build on what we’ve learned in 15 years of Java 43
  • 44. New Frontiers in Concurrency • There are several options now on the JVM – New possibilities built-in to the language syntax – Synch and asynch models • Scala offers an Actors model – And the powerful Akka framework • Clojure is immutable by default – Has agents (like actors) & shared-nothing by default – Also has a Software Transactional Memory (STM) model • Groovy has GPARs 44
  • 45. Acknowledgments • All otter images Creative Commons or Fair Use • Matt Raible • Ola Bini • 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 45
  • 46. Where is our beer!? 46
  • 47. Thanks for listening! (@kittylyst, @karianna) • http://www.teamsparq.net • http://www.java7developer.com 47

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. * Hands up for Java 6, 5, 4....\n* Hands up for j.u.c\n
  6. Hands up if you’re daunted by the refactoring that would be required\n\n
  7. \n
  8. \n
  9. They are Apex Predators - think of them in that same way\n
  10. The practice of managing your threads (or Otters!) is governed by four forces (after Doug Lea)\n
  11. \n
  12. \n
  13. It’s a little-known fact that Otters are scared of log-linear graphs\n
  14. Very successful within own frame of reference, but caveats\nReference Mechanical sympathy again here\n
  15. * So you can contort more and more, but you’re chasing diminishing returns\n* Ultimately, that exponent gap between clock speed and memory will do for you\n
  16. * 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
  17. * Explain that we’re going to show replacements for using synchronized\n* Raise your hand if you know why we use the keyword “synchronized” to denote a critical section in Java\n
  18. \n
  19. How performant do we think FS objects are?\nImmutability is good, but watch the copy-cost\n
  20. happens-before defines a “partial order” (if you’re a mathematician)\nJMM is even worse than the generics constraints part of the spec!\n\n
  21. * Hands up if you know what a NUMA architecture is?\n* In some ways, this is actually easier to explain on a NUMA arch...\n
  22. \n
  23. Lock can in some cases directly replace synchronized, but is more flexible\nMONITORENTER & MONITOREXIT\nWe use reentrant lock else recursive code deadlocks real quick\n
  24. \n
  25. Condition takes the place of wait() / notify() (Object monitors)\nTalk to the cases - 1 putter, 1 taker, many putters, few takers, few putters, many takers - think about this stuff at the design stage\n
  26. \n
  27. Basically it’s a drop-in replacement for regular HashMap\n“What’s the worst thing that can happen if you’re iterating over the keys of a regular HashMap and someone alters it underneath you?”\n
  28. Not quite a drop-in replacement - Performance needs to be thought about\nMV: Need to fix code sample so we have iterators\n
  29. \n
  30. \n
  31. BlockingQueue offers several different ways to interact with it (see the Javadoc)\n\n
  32. \n
  33. offer is similar to add but doesn’t throw exceptions\nProducers adding trade orders for example\nTheatresports\n
  34. Final building block for modern concurrent applications with Java\n
  35. \n
  36. Let’s step through a quasi-realistic example\nThat cancel() code begs for some of that lambda treatment huh!\n
  37. \n
  38. As well as RecursiveAction there’s the more general ForkJoinTask\n\n
  39. Multithreaded Quicksort - shows a speedup from O(nlog n) to O(n) - not quite linear, but not bad\n
  40. So this is pretty much a statement of the state-of-the-art in Java concurrency\n
  41. * Thread is the assembly language of concurrency\n* We need to move to a more managed model\n
  42. \n
  43. Coroutines, etc \nLMAX’s OSS “Disruptor” framework proves this\n
  44. \n
  45. \n
  46. \n
  47. \n