SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a 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
 

Similar a 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
 

Último

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdfMuhammad Subhan
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideStefan Dietze
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024Stephen Perrenod
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 

Último (20)

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 

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