SlideShare a Scribd company logo
1 of 26
Download to read offline
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

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
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingRobert Brown
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsRobert Brown
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsShashank L
 
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
 

What's hot (20)

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
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
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
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Core java
Core javaCore java
Core java
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Java 8 new features
Java 8 new features Java 8 new features
Java 8 new features
 
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
 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
 
Fork Join
Fork JoinFork Join
Fork Join
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
 

Viewers also liked

Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeJava 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeNikita Lipsky
 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionStephen Colebourne
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)Robert Scholte
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9Trisha Gee
 

Viewers also liked (12)

Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeJava 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introduction
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
 

Similar to Working With Concurrency In Java 8

TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleNoam Kfir
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
FRONTEND BOOTCAMP Session 2.pptx
FRONTEND BOOTCAMP Session 2.pptxFRONTEND BOOTCAMP Session 2.pptx
FRONTEND BOOTCAMP Session 2.pptxEhtesham46
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"Kazuhiro Sera
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Pipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei MccollumPipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei MccollumLorelei McCollum
 
Writing Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloWriting Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloDan Cuellar
 
Jose Luis Soria - XP2014 - Designing a Release Pipeline
Jose Luis Soria - XP2014 - Designing a Release PipelineJose Luis Soria - XP2014 - Designing a Release Pipeline
Jose Luis Soria - XP2014 - Designing a Release PipelineJose Luis Soria
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applicationsLari Hotari
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Martijn Verburg
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel StreamTengwen Wang
 

Similar to Working With Concurrency In Java 8 (20)

TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Eurosport's Kodakademi #2
Eurosport's Kodakademi #2Eurosport's Kodakademi #2
Eurosport's Kodakademi #2
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
FRONTEND BOOTCAMP Session 2.pptx
FRONTEND BOOTCAMP Session 2.pptxFRONTEND BOOTCAMP Session 2.pptx
FRONTEND BOOTCAMP Session 2.pptx
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Pipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei MccollumPipeline 101 Lorelei Mccollum
Pipeline 101 Lorelei Mccollum
 
Writing Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloWriting Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of Jello
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Jose Luis Soria - XP2014 - Designing a Release Pipeline
Jose Luis Soria - XP2014 - Designing a Release PipelineJose Luis Soria - XP2014 - Designing a Release Pipeline
Jose Luis Soria - XP2014 - Designing a Release Pipeline
 
Java and the JVM
Java and the JVMJava and the JVM
Java and the JVM
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applications
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Recently uploaded (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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.