SlideShare a Scribd company logo
WORKING WITH
CONCURRENCY IN JAVA 8
Designing & developing concurrent applications using Java 8.
Presenter: Heartin Jacob Kanikathottu
DISCLAIMER!
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help
you guide towards that goal. Sometimes it helps just to know that there is some API that
might be suitable for a particular situation. Make use of the pointers given to search
more and learn more on those topics. Refer to books, Java API Documentation, Blogs
etc. to learn more. Examples for all cases discussed will be added to my blog
www.javajee.com. I usually stress on few slides and run through few others, based on
the type of audience I am presenting. Fresher's or new developers might find the initial
slides more interesting whereas experienced Java developers may like the latter slides
more. Please check the references section for the books and resources I have referred
for preparing this. Please contact me for any queries or clarifications.
TOPICS
• Basic Java Concurrency Concepts
• Fork / Join Framework
• Concurrency in Java 8, with tips and tricks
• Steps to design concurrent applications
• Additional Tips and Tricks
• Demos
• Resources
PART 1 – BASIC JAVA CONCURRENCY
CONCEPTS
• Quick Intro to Java Concurrency API
• Quick Look into Basic Concurrency Concepts
• Why concurrency?
• Synchronization mechanisms
• Thread safety
• Synchronization problems
• Concurrency Design Principles
QUICK INTRO TO CONCURRENCY API
• Improved always through different versions of Java
• Thread, Runnable from Java 1.0,ThreadLocal from 1.2.
• Java 5 had introduced the Executor framework.
• Java 6 had minimal changes related to concurrency
• Java 7 introduced the Fork/Join framework and the Phaser.
• Java 8 has introduced Stream API along with many other classes.
• Concurrency API also includes many concurrent data structures and synchronous
mechanisms.
BASIC CONCURRENCY CONCEPTS
• Improve performance utilizing all the cores.
• Synchronization
• Semaphore to controlling access to a common resource.
• Monitor to get mutual exclusion over a shared resource.
• Thread safety
• Immutable objects to get thread safety without explicit synchronization.
• Atomic variables with atomic operations.
• Synchronization problems
• Race condition, Deadlock, Livelock, Resource Starvation, Priority Inversion.
CONCURRENCY DESIGN PRINCIPLES
• Signaling
• Notify event to another task.
• Rendezvous –
• Generalization of Signaling: Notify each other
• Mutex
• Critical section ensuring mutual exclusion.
• Multiplex –
• Generalization of Mutex: Determined number can execute the critical section.
• Can be implemented using Semaphore.
CONCURRENCY DESIGN PRINCIPLES
(COND..)
• Barrier
• Synchronize tasks at a common point.
• CyclicBarrier implement this pattern.
• Read-write lock
• Write happen alone, read can happen in parallel.
• Implemented by ReentrantReadWriteLock
• Double check locking
• Thread pool
• Thread local storage.
PART 2 - FORK/JOIN FRAMEWORK
• Intro to Fork /Join Framework
• Fork / Join Framework components
• Fork / join Methods
• Limitations of Fork / Join Framework
INTRO TO FORK / JOIN FRAMEWORK
• Special kind of Executor
• For divide and conquer solutions
• Uses work stealing algorithm
• Tasks attempt to find (steal) tasks submitted b other tasks
• Avoid threads waiting for work
• Used by many implementations internally in Java 8, such as parallelSort() or arrays,
parallel streams and even concurrent hash map.
FORK / JOIN COMPONENTS
• ForkJoinPool class
• Special executor with work stealing algorithm
• Java 8 includes a default ForkJoinPool called common pool.
• ForkJoinTask
• Abstract base task for tasks that run within a ForkJoinPool
• Provides fork() and join() methods and few variants
• RecursiveTask - Sub class that should be starting point for tasks that return a result.
• RecursiveAction – Sub class that should be starting point for tasks that don’t return result.
• CountedCompleter – Starting point for tasks that trigger other tasks when they are completed.
IMPORTANT FORK/JOIN METHODS
• Join vs quietlyJoin
• Join throws exception
• Quietly join will ignore exceptions
• Execute vs. invoke vs. submit
• Sends the task to ForkJoinPool
• Execute returns immediately a void value
• Invoke returns when the task has finished execution. Also have quetlyInvoke.
• Submit returns immediately a future object.
• Submit has also versions that accept Runnable and Callable.
LIMITATIONS OF FORK / JOIN
FRAMEWORK
• Problems could be solved using divide and conquer.
• Should not block on IO operations.
• Docn gives no work stealing guarantees in face of blocked IO or unmanaged
synchronization
• Can’t throw checked exceptions
• Should wrap exceptions into unchecked exceptions and handle them.
PART 3 - CONCURRENCY IN JAVA 8
• Important Concurrency Java 8 Additions
• Working with Parallel Streams
• Working with Atomic Variables
• Tips and Tricks for working with Concurrency APIs in Java 8
IMPORTANT JAVA 8 CONCURRENCY
ADDITIONS
• Stream API, Lambda expressions and Parallel streams
• Stamped Lock
• Parallel sort for arrays
• Default ForkJoinPool: Common pool.
• CountedCompleter
• CompletableFuture
• Double Added, LongAdder, DoubleAccumulator, LongAccumulator.
• New methods in Collection, ConcurrentMap and ConcurrentHashMap
WORKING WITH PARALLEL STREAMS
• Stream() vs. parallelStream() in Collection interface
• Arrays do no have a parallelStream() method.
• Parallel() vs. sequential()
• Parallel streams internally uses fork/join framework
• Elements may be processed in any order in parallel streams
• Avoid using stateful operations or that based on order within parallel streams
• Operations that depend on previous state like a loop iteration that is based on previous.
• E.g. Sorted, findFirt.
WORKING WITH ATOMIC VARIABLES
• DoubleAdder
• preferable to alternatives when frequently updated but less frequently read
• LongAdder
• under high contention, expected throughput of this class is significantly higher compared to
AtomicLong, at the expense of higher space consumption.
• DoubleAccumulator
• preferable to alternatives when frequently updated but less frequently read
• LongAccumulator
• under high contention, expected throughput of this class is significantly higher compared to
AtomicLong, at the expense of higher space consumption.
TIPS AND TRICKS
• Identify correct independent tasks.
• Use most appropriate atomic class for the situation.
• Find easily parallelizable version of algorithm.
• Use right identity while using reduce() with parallel streams.
• Avoid using stateful operations within parallel streams.
• Intermediate operations are not executed until a terminal operation (for all streams)
• Collect might be more efficient that reduce in most cases (for all streams)
TIPS AND TRICKS (COND..)
• Iterate() method of Stream interface should be avoided as much as possible.
• Most of the File class methods parallelize badly.
• SplittableRandom class is more suitable in parallel processing than Random class.
• Should use immutable objects as Identity object.
• All threads share the identity object in case of parallel streams.
• Parallelism threshold parameter of Concurrency methods should be used wisely.
• E.g. search(), reduce(), compute etc. of ConcurrentHashMap
• Parallel streams are not always the faster ones.
PART 4 – DESIGNING CONCURRENT
APPLICATIONS
• Steps to design concurrent applications
• Additional tips and tricks
• Demo: Merge Sort Sequential and Parallel Versions.
• Demo: Additional Java 8 Parallel Streams methods.
STEPS TO DESIGN CONCURRENT
APPLICATIONS
• Look for: Efficiency, Simplicity, Portability, Scalability.
• Starting point:
• A sequential version of algorithm.
• Can verify for correctness.
• Can see if performance really improves.
• Step 1: Analysis –
• Find good candidates.
• E.g. Loops whose iteration does not depend on previous iterations.
STEPS TO DESIGN CONCURRENT
APPLICATIONS (COND..)
• Step 2: Design
• Task decomposition, Data decomposition
• Step 3: Implement
• Implement using a programming language.
• Step 4:Test
• Test and compare against sequential
• Step 5:Tuning
• Speedup, Amdahl’s law, Gustafson-Barsis’ Law.
ADDITIONAL TIPS AND TRICKS
• Use higher level abstractions.
• Look for Scalability
• Use thread safe APIs when needed
• Never assume an execution order
• Avoid deadlocks by ordering locks
• Prefer local thread variables over static and shared
• Hold locks for as short time as possible
ADDITIONAL TIPS AND TRICKS (CONTD..)
• Use immutable objects
• Use atomic variables instead of synchronization
• Avoid use of blocking operations within critical sections.
• Always refer to Java API Documentation when in doubt.
RESOURCES & REFERENCES
• Java Concurrency in Practice
• by Brian Goetz,Tim Peierls , Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea
• Mastering Concurrency Programming with Java 8
• by Javier Fernandez Gonzalez
• www.JavaJee.com
• For my personal notes and examples. Got to Java section and look for multithreading.
• Oracle Java API Documentation: Ultimate place to look for anything.
WHAT NEXT?
• There is a lot more to learn.
• Continue learning together.
• Free after session support for continuous learning. J
• Contact me through www.javajee.com for any queries or doubts. Discuss any query
through the Timeline section or the Forum section, or even the contact page.

More Related Content

What's hot (20)

PPTX
Concurrency
Ankur Maheshwari
 
PPTX
The Java memory model made easy
Rafael Winterhalter
 
PDF
camel-scala.pdf
Hiroshi Ono
 
PDF
Concurrency
Isaac Liao
 
PPT
Core java
kasaragaddaslide
 
PPTX
The Java Memory Model
CA Technologies
 
PDF
Concurrency
Sri Prasanna
 
KEY
Automatic Reference Counting
Robert Brown
 
PDF
Concurrency Utilities in Java 8
Martin Toshev
 
KEY
Grand Central Dispatch Design Patterns
Robert Brown
 
PPTX
Effective java - concurrency
feng lee
 
PDF
Java Memory Model
Łukasz Koniecki
 
PDF
Introduction to concurrent programming with Akka actors
Shashank L
 
PDF
Java 8 new features
Tân Nguyễn Văn
 
PDF
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
PDF
Android concurrency
Ruslan Novikov
 
PPTX
Fork Join
Dmitry Buzdin
 
PDF
Java8 features
Minal Maniar
 
KEY
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
PPTX
Multithreading and concurrency in android
Rakesh Jha
 
Concurrency
Ankur Maheshwari
 
The Java memory model made easy
Rafael Winterhalter
 
camel-scala.pdf
Hiroshi Ono
 
Concurrency
Isaac Liao
 
Core java
kasaragaddaslide
 
The Java Memory Model
CA Technologies
 
Concurrency
Sri Prasanna
 
Automatic Reference Counting
Robert Brown
 
Concurrency Utilities in Java 8
Martin Toshev
 
Grand Central Dispatch Design Patterns
Robert Brown
 
Effective java - concurrency
feng lee
 
Java Memory Model
Łukasz Koniecki
 
Introduction to concurrent programming with Akka actors
Shashank L
 
Java 8 new features
Tân Nguyễn Văn
 
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
Android concurrency
Ruslan Novikov
 
Fork Join
Dmitry Buzdin
 
Java8 features
Minal Maniar
 
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
Multithreading and concurrency in android
Rakesh Jha
 

Viewers also liked (12)

PDF
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
PPT
Java 8 Streams
Manvendra Singh
 
PPTX
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
PDF
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
PPTX
Lambda Expressions in Java 8
icarter09
 
PDF
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
PDF
Java 8 Stream API. A different way to process collections.
David Gómez García
 
PDF
Lambda Expressions in Java
Erhan Bagdemir
 
PDF
Java 8 Lambda Expressions & Streams
NewCircle Training
 
PDF
Parallel streams in java 8
David Gómez García
 
PPTX
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
PDF
Real World Java 9
Trisha Gee
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Java 8 Streams
Manvendra Singh
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
Lambda Expressions in Java 8
icarter09
 
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Lambda Expressions in Java
Erhan Bagdemir
 
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Parallel streams in java 8
David Gómez García
 
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
Real World Java 9
Trisha Gee
 
Ad

Similar to Working With Concurrency In Java 8 (20)

PDF
Concurrent Programming in Java
Lakshmi Narasimhan
 
PDF
Concurrency in Java
Lakshmi Narasimhan
 
PDF
Java Tutorials - Concurrency
Christian Rubiales
 
PPTX
Concurrent talk
rahulrevo
 
PDF
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...
Anand Narayanan
 
PPTX
Concurrency - Why it's hard ?
Ramith Jayasinghe
 
KEY
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
PPTX
parallel-asynchronous-programming-java.pptx
2022ac05156
 
ODP
Java concurrency
Srinivasan Raghvan
 
PDF
What is new in java 8 concurrency
kshanth2101
 
PDF
Performance van Java 8 en verder - Jeroen Borgers
NLJUG
 
PPTX
Why Concurrency is hard ?
Ramith Jayasinghe
 
PDF
JAVA Interview Questions (1)............pdf
prasadkhotkar916
 
PDF
JAVA Interview Questions (1)..........pdf
prasadkhotkar916
 
ODP
Concurrent Programming in Java
Ruben Inoto Soto
 
KEY
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
PDF
Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec
trddarvai
 
PDF
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
PROIDEA
 
ODP
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
PDF
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
EPAM_Systems_Bulgaria
 
Concurrent Programming in Java
Lakshmi Narasimhan
 
Concurrency in Java
Lakshmi Narasimhan
 
Java Tutorials - Concurrency
Christian Rubiales
 
Concurrent talk
rahulrevo
 
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...
Anand Narayanan
 
Concurrency - Why it's hard ?
Ramith Jayasinghe
 
Modern Java Concurrency (OSCON 2012)
Martijn Verburg
 
parallel-asynchronous-programming-java.pptx
2022ac05156
 
Java concurrency
Srinivasan Raghvan
 
What is new in java 8 concurrency
kshanth2101
 
Performance van Java 8 en verder - Jeroen Borgers
NLJUG
 
Why Concurrency is hard ?
Ramith Jayasinghe
 
JAVA Interview Questions (1)............pdf
prasadkhotkar916
 
JAVA Interview Questions (1)..........pdf
prasadkhotkar916
 
Concurrent Programming in Java
Ruben Inoto Soto
 
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec
trddarvai
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
PROIDEA
 
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Tech Talks_04.07.15_Session 3_Martin Toshev_Concurrency Utilities In Java 8
EPAM_Systems_Bulgaria
 
Ad

Recently uploaded (20)

PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Q2 Leading a Tableau User Group - Onboarding
lward7
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
July Patch Tuesday
Ivanti
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Q2 Leading a Tableau User Group - Onboarding
lward7
 

Working With Concurrency In Java 8

  • 1. WORKING WITH CONCURRENCY IN JAVA 8 Designing & developing concurrent applications using Java 8. Presenter: Heartin Jacob Kanikathottu
  • 2. DISCLAIMER! Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples for all cases discussed will be added to my blog www.javajee.com. I usually stress on few slides and run through few others, based on the type of audience I am presenting. Fresher's or new developers might find the initial slides more interesting whereas experienced Java developers may like the latter slides more. Please check the references section for the books and resources I have referred for preparing this. Please contact me for any queries or clarifications.
  • 3. TOPICS • Basic Java Concurrency Concepts • Fork / Join Framework • Concurrency in Java 8, with tips and tricks • Steps to design concurrent applications • Additional Tips and Tricks • Demos • Resources
  • 4. PART 1 – BASIC JAVA CONCURRENCY CONCEPTS • Quick Intro to Java Concurrency API • Quick Look into Basic Concurrency Concepts • Why concurrency? • Synchronization mechanisms • Thread safety • Synchronization problems • Concurrency Design Principles
  • 5. QUICK INTRO TO CONCURRENCY API • Improved always through different versions of Java • Thread, Runnable from Java 1.0,ThreadLocal from 1.2. • Java 5 had introduced the Executor framework. • Java 6 had minimal changes related to concurrency • Java 7 introduced the Fork/Join framework and the Phaser. • Java 8 has introduced Stream API along with many other classes. • Concurrency API also includes many concurrent data structures and synchronous mechanisms.
  • 6. BASIC CONCURRENCY CONCEPTS • Improve performance utilizing all the cores. • Synchronization • Semaphore to controlling access to a common resource. • Monitor to get mutual exclusion over a shared resource. • Thread safety • Immutable objects to get thread safety without explicit synchronization. • Atomic variables with atomic operations. • Synchronization problems • Race condition, Deadlock, Livelock, Resource Starvation, Priority Inversion.
  • 7. CONCURRENCY DESIGN PRINCIPLES • Signaling • Notify event to another task. • Rendezvous – • Generalization of Signaling: Notify each other • Mutex • Critical section ensuring mutual exclusion. • Multiplex – • Generalization of Mutex: Determined number can execute the critical section. • Can be implemented using Semaphore.
  • 8. CONCURRENCY DESIGN PRINCIPLES (COND..) • Barrier • Synchronize tasks at a common point. • CyclicBarrier implement this pattern. • Read-write lock • Write happen alone, read can happen in parallel. • Implemented by ReentrantReadWriteLock • Double check locking • Thread pool • Thread local storage.
  • 9. PART 2 - FORK/JOIN FRAMEWORK • Intro to Fork /Join Framework • Fork / Join Framework components • Fork / join Methods • Limitations of Fork / Join Framework
  • 10. INTRO TO FORK / JOIN FRAMEWORK • Special kind of Executor • For divide and conquer solutions • Uses work stealing algorithm • Tasks attempt to find (steal) tasks submitted b other tasks • Avoid threads waiting for work • Used by many implementations internally in Java 8, such as parallelSort() or arrays, parallel streams and even concurrent hash map.
  • 11. FORK / JOIN COMPONENTS • ForkJoinPool class • Special executor with work stealing algorithm • Java 8 includes a default ForkJoinPool called common pool. • ForkJoinTask • Abstract base task for tasks that run within a ForkJoinPool • Provides fork() and join() methods and few variants • RecursiveTask - Sub class that should be starting point for tasks that return a result. • RecursiveAction – Sub class that should be starting point for tasks that don’t return result. • CountedCompleter – Starting point for tasks that trigger other tasks when they are completed.
  • 12. IMPORTANT FORK/JOIN METHODS • Join vs quietlyJoin • Join throws exception • Quietly join will ignore exceptions • Execute vs. invoke vs. submit • Sends the task to ForkJoinPool • Execute returns immediately a void value • Invoke returns when the task has finished execution. Also have quetlyInvoke. • Submit returns immediately a future object. • Submit has also versions that accept Runnable and Callable.
  • 13. LIMITATIONS OF FORK / JOIN FRAMEWORK • Problems could be solved using divide and conquer. • Should not block on IO operations. • Docn gives no work stealing guarantees in face of blocked IO or unmanaged synchronization • Can’t throw checked exceptions • Should wrap exceptions into unchecked exceptions and handle them.
  • 14. PART 3 - CONCURRENCY IN JAVA 8 • Important Concurrency Java 8 Additions • Working with Parallel Streams • Working with Atomic Variables • Tips and Tricks for working with Concurrency APIs in Java 8
  • 15. IMPORTANT JAVA 8 CONCURRENCY ADDITIONS • Stream API, Lambda expressions and Parallel streams • Stamped Lock • Parallel sort for arrays • Default ForkJoinPool: Common pool. • CountedCompleter • CompletableFuture • Double Added, LongAdder, DoubleAccumulator, LongAccumulator. • New methods in Collection, ConcurrentMap and ConcurrentHashMap
  • 16. WORKING WITH PARALLEL STREAMS • Stream() vs. parallelStream() in Collection interface • Arrays do no have a parallelStream() method. • Parallel() vs. sequential() • Parallel streams internally uses fork/join framework • Elements may be processed in any order in parallel streams • Avoid using stateful operations or that based on order within parallel streams • Operations that depend on previous state like a loop iteration that is based on previous. • E.g. Sorted, findFirt.
  • 17. WORKING WITH ATOMIC VARIABLES • DoubleAdder • preferable to alternatives when frequently updated but less frequently read • LongAdder • under high contention, expected throughput of this class is significantly higher compared to AtomicLong, at the expense of higher space consumption. • DoubleAccumulator • preferable to alternatives when frequently updated but less frequently read • LongAccumulator • under high contention, expected throughput of this class is significantly higher compared to AtomicLong, at the expense of higher space consumption.
  • 18. TIPS AND TRICKS • Identify correct independent tasks. • Use most appropriate atomic class for the situation. • Find easily parallelizable version of algorithm. • Use right identity while using reduce() with parallel streams. • Avoid using stateful operations within parallel streams. • Intermediate operations are not executed until a terminal operation (for all streams) • Collect might be more efficient that reduce in most cases (for all streams)
  • 19. TIPS AND TRICKS (COND..) • Iterate() method of Stream interface should be avoided as much as possible. • Most of the File class methods parallelize badly. • SplittableRandom class is more suitable in parallel processing than Random class. • Should use immutable objects as Identity object. • All threads share the identity object in case of parallel streams. • Parallelism threshold parameter of Concurrency methods should be used wisely. • E.g. search(), reduce(), compute etc. of ConcurrentHashMap • Parallel streams are not always the faster ones.
  • 20. PART 4 – DESIGNING CONCURRENT APPLICATIONS • Steps to design concurrent applications • Additional tips and tricks • Demo: Merge Sort Sequential and Parallel Versions. • Demo: Additional Java 8 Parallel Streams methods.
  • 21. STEPS TO DESIGN CONCURRENT APPLICATIONS • Look for: Efficiency, Simplicity, Portability, Scalability. • Starting point: • A sequential version of algorithm. • Can verify for correctness. • Can see if performance really improves. • Step 1: Analysis – • Find good candidates. • E.g. Loops whose iteration does not depend on previous iterations.
  • 22. STEPS TO DESIGN CONCURRENT APPLICATIONS (COND..) • Step 2: Design • Task decomposition, Data decomposition • Step 3: Implement • Implement using a programming language. • Step 4:Test • Test and compare against sequential • Step 5:Tuning • Speedup, Amdahl’s law, Gustafson-Barsis’ Law.
  • 23. ADDITIONAL TIPS AND TRICKS • Use higher level abstractions. • Look for Scalability • Use thread safe APIs when needed • Never assume an execution order • Avoid deadlocks by ordering locks • Prefer local thread variables over static and shared • Hold locks for as short time as possible
  • 24. ADDITIONAL TIPS AND TRICKS (CONTD..) • Use immutable objects • Use atomic variables instead of synchronization • Avoid use of blocking operations within critical sections. • Always refer to Java API Documentation when in doubt.
  • 25. RESOURCES & REFERENCES • Java Concurrency in Practice • by Brian Goetz,Tim Peierls , Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea • Mastering Concurrency Programming with Java 8 • by Javier Fernandez Gonzalez • www.JavaJee.com • For my personal notes and examples. Got to Java section and look for multithreading. • Oracle Java API Documentation: Ultimate place to look for anything.
  • 26. WHAT NEXT? • There is a lot more to learn. • Continue learning together. • Free after session support for continuous learning. J • Contact me through www.javajee.com for any queries or doubts. Discuss any query through the Timeline section or the Forum section, or even the contact page.