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

Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceDeon Huang
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best PracticesIndicThreads
 
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 contentRS Trainings
 
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...Bob Pusateri
 
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 28Ruby Meditation
 

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

Uc123 pal presentation deck
Uc123 pal presentation deckUc123 pal presentation deck
Uc123 pal presentation deckjeffguillet
 
Slide sesi 6 - java concurrency
Slide   sesi 6 - java concurrencySlide   sesi 6 - java concurrency
Slide sesi 6 - java concurrencyPetra Barus
 
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)Amila Paranawithana
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
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.5Peter Antman
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
6장 Thread Synchronization
6장 Thread Synchronization6장 Thread Synchronization
6장 Thread Synchronization김 한도
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 

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_20120410huangachou
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10huangachou
 
Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Modern Java Concurrency (OSCON 2012)
Modern Java Concurrency (OSCON 2012)Martijn Verburg
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Martijn Verburg
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programmingTausun Akhtary
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Ramith Jayasinghe
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
Multithreading in Scala
Multithreading in Scala Multithreading in Scala
Multithreading in Scala Knoldus Inc.
 
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 toolsHaribabu Nandyal Padmanaban
 
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...Sachintha Gunasena
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuningosa_ora
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 

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

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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.pdfsudhanshuwaghmare1
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
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
 
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 CVKhem
 
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
 
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
 
[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
 
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?Igalia
 
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
 
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
 

Dernier (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
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
 
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
 
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...
 
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
 
[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
 
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?
 
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...
 
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
 

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