SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Java & Concurrency
Lakshmi Narasimhan
2
Agenda
 United at birth
 Why more relevant now
 Concurrency over the years
 Basics & Myths
 Concurrency Patterns
 Deep-dive
 There's more than one way to solve it!!
 Common gotchas
 Q&A
3
Java & Concurrency : United at birth
●
In-built into the language
●
Not an after thought
●
Support for threads from Day 1
●
Everything is a monitor
●
Simplicity over complexity
●
Multiple inheritance
●
Operator overloading
●
Choice of languages
●
Scala, Clojure
4
Why is it more relevant now
• H/W & S/W trends
– No longer privilege of few
– Scaling accentuates Vertical and horizontal scaling mean more
complexity
– Distributed caches, faster I/O
– Weak Cache coherence
• Application requirements
– Impunity of slow system lifted
– Elasticity is the mantra
– The weakest link draws the whole system down
– Bottlenecks can be really really costly
5
Concurrency over the years
Java VersionJava Version FeaturesFeatures
JDK 1.0 ●Threads
●“synchronized” keyword
●HashTable(thread-safe but synchronized classes)
JDK 1.2 ●Collections framework(updated)
●un-synchronized classes bound by
synchronized accessors
●eg: Collections.synchronizedMap()
●Use when you need sync
JDK 1.5 ● concurrency package JSR166 java.util.concurrent
JDK 7 ● Updated java.util.concurrent package(JSR166y)
Fork-Join and Executor Framework
JDK 8 ● Modularity
● Lamda
6
Concurrency : Basics
Three elements of a concurrent Application

Atomicity

Certain pieces of an application must all be executed as one unit
●
Visibility

Changes that you make to a value to be visible precisely when you intend them to
be
●
Synchronization

Concurrent access to shared variables should be guarded
Terms you will come across
●
JMM – The specification that guarantees how the JVM should work
●
Monitor – Intrinsic lock (Every object has a monitor associated with it)
●
Race condition – An operation on shared resources whose outcome may be in-
deterministic
●

7
Concurrency : Myths
●
The more the threads, faster my application is
• A bigger system means faster execution
• Processors/compilers can optimize my code for
parallelism
• Locks make the program go slow
• Re-factoring is easy
• Writing concurrent application is a black-art
8
Common concurrency patterns
Dynamic Exclusion Through Implicit Locks
• a.k.a “synchronized”
• Lock obtained if method is declared synchronized
• Watch out for fine/coarse grained locks.
• Dos/Dont's:
– Avoid CPU/IO intensive operations inside “synchronized” block.
– “synchronize” on a code block and not method (if appropriate)
• Remember that JIT can re-order execution
9
Common concurrency patterns
Structural Exclusion Through Confinement
• Options:
– Thread confinement : Access object from a single thread using
thread-per-session approach
– Instance confinement : Use encapsulation techniques to restrict
access to object state from multiple threads
– Method confinement : Do not allow an object to escape from
method by referencing it through local variables
• Do's/Dont's:
– Confinement cannot be relied on unless a design is leak proof
– Combine confinement with appropriate locking discipline
– Use ThreadLocal variables to maintain Thread Confinement
10
Common concurrency patterns
Immutability
• Object state cannot change after construction
• Are automatically thread-safe
• Immutability is guranteed only when :
– All fields are declared final
– Object reference fields must not allow modifications anywhere in the object
graph reachable from the fields after construction
– The class should be declared final (to prevent a subclass from subverting
these rules)
• Immutable objects eliminate a bunch of issues around concurrency. Use whenever you
can.
• Have “failure atomicity” - upon an exception, state is never undesirable or
indeterministic.
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot
be made immutable, limit its mutability as much as possible." - Joshua Blochbe made immutable, limit its mutability as much as possible." - Joshua Bloch
11
Common concurrency patterns
Co-operation
• Wait-notify mechanisms
• One thread creates a condition and another one waits for it
• All threads are treated the same - when multiple threads are waiting,
no guarantee on which one would wake up
• Missed or early notifications
• Do's/Dont's:
– Use notifyAll() instead of notify()
– Wait() in a while loop
– Call wait() and notify() inside synchronized block
12
Deep Dive
• JSR166 - “java.util.concurrent” packages
• Introduced in JDK 5
• Motivation
– Creating APIs for commonly used functionality
– Application/scenario agnostic
– “volatile” guaranteed visibility but not atomicity
– Synchronization is expensive (and can cause dead-lock)
●
Atomic Variables, nanosecond timing, Condition variables, Lock classes,
tryLock, Queues, Barriers, Executors.....
●
13
Deep Dive – Atomic Classes
• java.util.concurrent.atomic.Atomic* classes
●
Provides a worthy substitute for “volatile” and “synchronized”
●
Available on Integer, Long, Boolean, Object Ref, Arrays
●
CompareAndSet(), incrementAndGet() etc guarantee atomicity
14
Deep Dive : Locks
ReentrantLock

“synchronization” on steroids

Supports Lock state, non-blocking tryLock() and interruptible locking

Throughput can be higher by order of magnitudes

Can be extended to set “fairness” and “Condition”







Use ONLY and ONLY if “synchronized” will not solve your problems

If your Application needs timed-locks, interruptible locks, multiple condition locks
15
Deep Dive : Executor Framework
●
Implemented via java.util.concurrent.ExecutorService
●
Provides flexible thread pool implementation
●
Producer-consumer pattern
– Producer : Creates work
– Consumer : Executes the work
●
●
●
●
●
Consider newCachedThreadPool if you don't want to bound no. of threads
16
Deep Dive : Executor Framework
●
Remember to shut it down
●
Asynchronous execution may hide hidden tasks
●
17
Deep Dive: Fork Join Framework
“Framework for supporting a style of programming in which problems are solved by recursively splitting them in
to sub tasks that are solved in parallel, waiting for them to complete and then composing results”
●
Introduced through JSR166y and part of Java 7
●
Introduces Parallel-Array (PA) concept to Java (simlar to Map-Reduce?)
●
Extends the executor framework for Recursive style problems
●
Makes use of work stealing algorithm
●
Transparent Parallelism requiring no tuning (almost!)
●
Suited for MMP Architectures.
●
Number of sub tasks can be altered at run-time

“Fork” Starts a new parallel fork/join subtask

“Join” causes current task not to proceed until the forked task is complete

This can happen recursively till tasks are smaller enough to be solved sequentially
Components of a FJ framework
●
The guy who does the work (business logic)
●
The guy who tells how the work can be split
●
The guy who coordinates it all (FJ)
18
There's more than one way to solve it
●
There's always more than one way to solve the problem
●
Know the pros/cons of each approach
●
Example :
Not Thread Safe
19
Option 1 : Using “volatile” keyword
Pros:
●
Simple, easy to write and understand
●
Would solve most of the requirement
Cons:
●
Thread looping
●
No option to know/set priority of waiting threads
There's more than one way to solve it
20
Option 2 : Using “AtomicBoolean”
Pros:
●
Fairly straight-forward
●
“tryLock()” can prevent costly thread spins
●
Flexibility to set Condition and “fairness” of waiting threads
Cons:
●
Slight over-head if you need primitive data locking
There's more than one way to solve it
21
Option 3 : Using “synchronized”
Pros:
●
Locks are intrinsic and so no need to release them explicitly
Cons
●
Code is a lot more verbose
●
Empty thread looping
There's more than one way to solve it
22
Common concurrency mistakes
●
synchronization
– Fine/coarse grained synchronization
– Synchronizing just data
– Validating data integrity at one level
– Synchronizing on “null”
– Changing synchronizing object instance
– Synchronizing on string literals
– Writing with synchronization but reading w/o it
– Volatile array -
• “valarr” is a volatile reference to an array, but array elements are not
23
Common concurrency mistakes
●
Volatile will work only when
– write to variable does not depend on current value
– Write does not depend on any other non-atomic operation
●
CachedThreadPool is un-bound – You may run out of resources
sooner than you thought
●
●
The list never ends.....
●
Recommend go through “Java Platform Concurrency Gotchas”
- Alex Miller
●
24
Re-cap
 Relevance of concurrency
 Basics & Myths
 Concurrency Patterns
 Deep-dive
 There's more than one way to solve it!!
 Common gotchas
 Q&A

Contenu connexe

Tendances

Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
IndicThreads
 

Tendances (7)

Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Ruby Concurrency
Ruby ConcurrencyRuby Concurrency
Ruby Concurrency
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
 
Java (advanced and core)online training in Hyderabad|course content
Java (advanced and core)online training in Hyderabad|course contentJava (advanced and core)online training in Hyderabad|course content
Java (advanced and core)online training in Hyderabad|course content
 
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
 
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28
 
Java Threading
Java ThreadingJava Threading
Java Threading
 

En vedette

exception handling in java
exception handling in java exception handling in java
exception handling in java
aptechsravan
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 

En vedette (20)

Uc123 pal presentation deck
Uc123 pal presentation deckUc123 pal presentation deck
Uc123 pal presentation deck
 
Slide sesi 6 - java concurrency
Slide   sesi 6 - java concurrencySlide   sesi 6 - java concurrency
Slide sesi 6 - java concurrency
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 
Threads concurrency identifying performance deviations in thread pools(1)
Threads concurrency   identifying performance deviations in thread pools(1)Threads concurrency   identifying performance deviations in thread pools(1)
Threads concurrency identifying performance deviations in thread pools(1)
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
Android ui menu
Android ui menuAndroid ui menu
Android ui menu
 
Exception handling
Exception handlingException handling
Exception handling
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
6장 Thread Synchronization
6장 Thread Synchronization6장 Thread Synchronization
6장 Thread Synchronization
 
android menus
android menusandroid menus
android menus
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Similaire à Concurrency in Java

Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410
huangachou
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
huangachou
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
Dmitry Buzdin
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 

Similaire à Concurrency in Java (20)

Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Why Concurrency is hard ?
Why Concurrency is hard ?Why Concurrency is hard ?
Why Concurrency is hard ?
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading in Scala
Multithreading in Scala Multithreading in Scala
Multithreading in Scala
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
 
Java threading
Java threadingJava threading
Java threading
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Concurrency in Java

  • 2. 2 Agenda  United at birth  Why more relevant now  Concurrency over the years  Basics & Myths  Concurrency Patterns  Deep-dive  There's more than one way to solve it!!  Common gotchas  Q&A
  • 3. 3 Java & Concurrency : United at birth ● In-built into the language ● Not an after thought ● Support for threads from Day 1 ● Everything is a monitor ● Simplicity over complexity ● Multiple inheritance ● Operator overloading ● Choice of languages ● Scala, Clojure
  • 4. 4 Why is it more relevant now • H/W & S/W trends – No longer privilege of few – Scaling accentuates Vertical and horizontal scaling mean more complexity – Distributed caches, faster I/O – Weak Cache coherence • Application requirements – Impunity of slow system lifted – Elasticity is the mantra – The weakest link draws the whole system down – Bottlenecks can be really really costly
  • 5. 5 Concurrency over the years Java VersionJava Version FeaturesFeatures JDK 1.0 ●Threads ●“synchronized” keyword ●HashTable(thread-safe but synchronized classes) JDK 1.2 ●Collections framework(updated) ●un-synchronized classes bound by synchronized accessors ●eg: Collections.synchronizedMap() ●Use when you need sync JDK 1.5 ● concurrency package JSR166 java.util.concurrent JDK 7 ● Updated java.util.concurrent package(JSR166y) Fork-Join and Executor Framework JDK 8 ● Modularity ● Lamda
  • 6. 6 Concurrency : Basics Three elements of a concurrent Application  Atomicity  Certain pieces of an application must all be executed as one unit ● Visibility  Changes that you make to a value to be visible precisely when you intend them to be ● Synchronization  Concurrent access to shared variables should be guarded Terms you will come across ● JMM – The specification that guarantees how the JVM should work ● Monitor – Intrinsic lock (Every object has a monitor associated with it) ● Race condition – An operation on shared resources whose outcome may be in- deterministic ● 
  • 7. 7 Concurrency : Myths ● The more the threads, faster my application is • A bigger system means faster execution • Processors/compilers can optimize my code for parallelism • Locks make the program go slow • Re-factoring is easy • Writing concurrent application is a black-art
  • 8. 8 Common concurrency patterns Dynamic Exclusion Through Implicit Locks • a.k.a “synchronized” • Lock obtained if method is declared synchronized • Watch out for fine/coarse grained locks. • Dos/Dont's: – Avoid CPU/IO intensive operations inside “synchronized” block. – “synchronize” on a code block and not method (if appropriate) • Remember that JIT can re-order execution
  • 9. 9 Common concurrency patterns Structural Exclusion Through Confinement • Options: – Thread confinement : Access object from a single thread using thread-per-session approach – Instance confinement : Use encapsulation techniques to restrict access to object state from multiple threads – Method confinement : Do not allow an object to escape from method by referencing it through local variables • Do's/Dont's: – Confinement cannot be relied on unless a design is leak proof – Combine confinement with appropriate locking discipline – Use ThreadLocal variables to maintain Thread Confinement
  • 10. 10 Common concurrency patterns Immutability • Object state cannot change after construction • Are automatically thread-safe • Immutability is guranteed only when : – All fields are declared final – Object reference fields must not allow modifications anywhere in the object graph reachable from the fields after construction – The class should be declared final (to prevent a subclass from subverting these rules) • Immutable objects eliminate a bunch of issues around concurrency. Use whenever you can. • Have “failure atomicity” - upon an exception, state is never undesirable or indeterministic. "Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible." - Joshua Blochbe made immutable, limit its mutability as much as possible." - Joshua Bloch
  • 11. 11 Common concurrency patterns Co-operation • Wait-notify mechanisms • One thread creates a condition and another one waits for it • All threads are treated the same - when multiple threads are waiting, no guarantee on which one would wake up • Missed or early notifications • Do's/Dont's: – Use notifyAll() instead of notify() – Wait() in a while loop – Call wait() and notify() inside synchronized block
  • 12. 12 Deep Dive • JSR166 - “java.util.concurrent” packages • Introduced in JDK 5 • Motivation – Creating APIs for commonly used functionality – Application/scenario agnostic – “volatile” guaranteed visibility but not atomicity – Synchronization is expensive (and can cause dead-lock) ● Atomic Variables, nanosecond timing, Condition variables, Lock classes, tryLock, Queues, Barriers, Executors..... ●
  • 13. 13 Deep Dive – Atomic Classes • java.util.concurrent.atomic.Atomic* classes ● Provides a worthy substitute for “volatile” and “synchronized” ● Available on Integer, Long, Boolean, Object Ref, Arrays ● CompareAndSet(), incrementAndGet() etc guarantee atomicity
  • 14. 14 Deep Dive : Locks ReentrantLock  “synchronization” on steroids  Supports Lock state, non-blocking tryLock() and interruptible locking  Throughput can be higher by order of magnitudes  Can be extended to set “fairness” and “Condition”        Use ONLY and ONLY if “synchronized” will not solve your problems  If your Application needs timed-locks, interruptible locks, multiple condition locks
  • 15. 15 Deep Dive : Executor Framework ● Implemented via java.util.concurrent.ExecutorService ● Provides flexible thread pool implementation ● Producer-consumer pattern – Producer : Creates work – Consumer : Executes the work ● ● ● ● ● Consider newCachedThreadPool if you don't want to bound no. of threads
  • 16. 16 Deep Dive : Executor Framework ● Remember to shut it down ● Asynchronous execution may hide hidden tasks ●
  • 17. 17 Deep Dive: Fork Join Framework “Framework for supporting a style of programming in which problems are solved by recursively splitting them in to sub tasks that are solved in parallel, waiting for them to complete and then composing results” ● Introduced through JSR166y and part of Java 7 ● Introduces Parallel-Array (PA) concept to Java (simlar to Map-Reduce?) ● Extends the executor framework for Recursive style problems ● Makes use of work stealing algorithm ● Transparent Parallelism requiring no tuning (almost!) ● Suited for MMP Architectures. ● Number of sub tasks can be altered at run-time  “Fork” Starts a new parallel fork/join subtask  “Join” causes current task not to proceed until the forked task is complete  This can happen recursively till tasks are smaller enough to be solved sequentially Components of a FJ framework ● The guy who does the work (business logic) ● The guy who tells how the work can be split ● The guy who coordinates it all (FJ)
  • 18. 18 There's more than one way to solve it ● There's always more than one way to solve the problem ● Know the pros/cons of each approach ● Example : Not Thread Safe
  • 19. 19 Option 1 : Using “volatile” keyword Pros: ● Simple, easy to write and understand ● Would solve most of the requirement Cons: ● Thread looping ● No option to know/set priority of waiting threads There's more than one way to solve it
  • 20. 20 Option 2 : Using “AtomicBoolean” Pros: ● Fairly straight-forward ● “tryLock()” can prevent costly thread spins ● Flexibility to set Condition and “fairness” of waiting threads Cons: ● Slight over-head if you need primitive data locking There's more than one way to solve it
  • 21. 21 Option 3 : Using “synchronized” Pros: ● Locks are intrinsic and so no need to release them explicitly Cons ● Code is a lot more verbose ● Empty thread looping There's more than one way to solve it
  • 22. 22 Common concurrency mistakes ● synchronization – Fine/coarse grained synchronization – Synchronizing just data – Validating data integrity at one level – Synchronizing on “null” – Changing synchronizing object instance – Synchronizing on string literals – Writing with synchronization but reading w/o it – Volatile array - • “valarr” is a volatile reference to an array, but array elements are not
  • 23. 23 Common concurrency mistakes ● Volatile will work only when – write to variable does not depend on current value – Write does not depend on any other non-atomic operation ● CachedThreadPool is un-bound – You may run out of resources sooner than you thought ● ● The list never ends..... ● Recommend go through “Java Platform Concurrency Gotchas” - Alex Miller ●
  • 24. 24 Re-cap  Relevance of concurrency  Basics & Myths  Concurrency Patterns  Deep-dive  There's more than one way to solve it!!  Common gotchas  Q&A