SlideShare une entreprise Scribd logo
1  sur  69
Télécharger pour lire hors ligne
THREADS AND JAVA MEMORY
MODEL EXPLAINED
LUIZ TESTON, WWW.FRACTA.CC
SOME QUOTES I
HEARD IN MY
CAREER
“DEAD LOCK ON 300 THREADS.
CAN ANYBODY HELP ME?”
Soft real time developer
“IN PARALLEL IT IS WORSE.”
// GLOBAL LOCK ON A HUGE GRAPH
Myself struggling to fix a performance issue
“LET’S NOT USE THREADS,
IT ALWAYS GIVES US
TROUBLE.”
Architect with 15 years of experience
“MY CODE WORKS.”
// NO SYNCHRONISATION, ONLY THREADS
Lead Programmer
DOING MANY
THINGS AT ONCE?
A FEW THINGS
YOU SHOULD
KNOW…
VOCABULARY
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
PARALLEL != CONCURRENT
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
PARALLEL DON'T DISPUTE,
CONCURRENT MAY DISPUTE.
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
X
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
PARALLELISM WON’T
IMPROVE LATENCY.
PARALLELISM MAY
IMPROVE THROUGHPUT.
JSR 133
JAVA
MEMORY MODEL
RACE CONDITION
THE CLASSIC
SAMPLE
RACE CONDITION
▸ definition: shared resources may get used “at the same
time” by different threads, resulting in a invalid state.
▸ motivation: any need of concurrent or parallel processing.
▸ how to avoid: usage of some mechanism to ensure
resources are used by only one thread at a time or even
share nothing.
thread 1 thread 2
VAR=0
thread 1 thread 2
VAR=0
VAR++ VAR++
thread 1 thread 2
VAR=0
VAR++ VAR++
VAR=1
Clearly not the
expected result. There
are code in production
working with those
errors for years without
people realising it.
VAR WAS NOT
SYNCHRONISED PROPERLY
AVOIDING OR FIXING THIS RACE CONDITION
▸ let the database deal with it (just kidding, but sadly it seems to
be the standard way of doing it).
▸ correct synchronisation by using locks.
▸ usage of concurrent classes, such as AtomicLong.
▸ one counter per thread (summing them still requires
synchronisation).
▸ share nothing.
▸ any other suggestion?
thread 1 thread 2
VAR=0LOCK
thread 1 thread 2
VAR=0LOCK
LOCK
VAR++ WAITING
LOCK
thread 1 thread 2
VAR=0LOCK
VAR++
LOCK
VAR++
thread 1 thread 2
VAR=0LOCK
VAR++
VAR++
VAR=2
The result was as
expected, but there
was a penalty in the
time it took to perform
both operations. In
order to minimise it
avoid sharing in the
first place.
VAR WAS
PROPERLY SYNCHRONISED
READS ALSO NEEDS
SYNCHRONISATION
// COMMON MISTAKE IS ONLY
// SYNCHRONISE WRITES.
LESSONS
▸ Synchronise properly. High level APIs are easier not to
mess with. java.util.concurrent excels at that.
▸ The optimal number of threads is usually twice the number
of cores: Runtime.getRuntime().availableProcessors() * 2;
▸ Measure and stress. It is not easy to see synchronisation
issues, since the behaviour varies depending on machine,
operation system, etc. They usually don’t show while
debugging.
DEAD LOCK
SOMETIMES
NEVER ENDS
DEAD LOCKS
▸ what it is: threads holding and waiting each other locks.
▸ motivation: global lock leads to global contention and
slow code. Use of more than one fine grained lock at the
same time in more than one thread in a unpredictable way
is the real problem.
▸ how to avoid: ensure same locking order or review
synchronisation strategy (functional approach, atomic
classes, high level APIs, concurrent collections, share
nothing, etc).
thread 1 thread 2
AB
Two threads have
access to resources
protected by two
distinct locks: A and B.
Green means available,
yellow means waiting
and red means locked.
Two scenarios are
going to be presented:
Threads acquiring the
locks in the same order,
and in different order.
thread 1 thread 2
B A First thread acquires
lock A.
thread 1 thread 2
B A A
Second thread tries to
acquire the same lock.
Since it is in use, it will
wait until lock A is
available.
thread 1 thread 2
A A
B
Meanwhile the first
thread acquires lock B.
The second thread is
still waiting for lock A.
thread 1 thread 2
B A A
The first thread
releases lock B. The
second thread is still
waiting for lock A.
thread 1 thread 2
AB A
Then the lock A is
finally released. The
second thread is finally
able to use it.
thread 1 thread 2
B A It acquires lock A.
thread 1 thread 2
A
B
Then it acquires lock B.
thread 1 thread 2
B A Lock B is released.
thread 1 thread 2
AB
Then lock A is released.
No synchronisation
problems has
happened and no
locked resources where
harmed in this
execution. Some
contention has
happened, but they
where temporary.
EVERYTHING WAS FINE.
thread 1 thread 2
AB NOW SOMETHING DIFFERENT
thread 1 thread 2
B A
The first thread
acquires lock A.
thread 1 thread 2
A B
And the second thread
acquires lock B.
thread 1 thread 2
A B
B
The first thread tries to
acquire lock B. Since it
is busy, it will wait for it.
thread 1 thread 2
A B
B A
And the second thread
tries to acquire lock A.
Since it is busy, it will
wait for it.
thread 1 thread 2
A B
B A
What did the different
order of lock
acquisition cause?
Keep in mind locks can
be acquired internally
by APIs, by using the
synchronised keyword,
by doing IO. It is almost
impossible to keep
track of all the locks in
a huge application
stack.
DEAD LOCK IS SET.
LESSONS
▸ If sharing data between threads, synchronise properly and
measure and stress (same as before).
▸ Keep in mind some dead locks keeps latent and may happen
only in unusual situations (such as unusual high peak load).
▸ The best approach is to minimise sharing data, having
isolated threads working independently.
▸ There are frameworks that suits better than using threads
manually. Consider those, such as Akka, Disruptor, etc.
QUESTIONS? THANKS FOR YOUR TIME!
▸ https://www.cs.umd.edu/~pugh/java/memoryModel/
jsr-133-faq.html
▸ http://docs.oracle.com/javase/specs/
▸ fotos: Dani Teston

Contenu connexe

Tendances

[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programmingraksharao
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)It Academy
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Clockless design language - ilia greenblat
Clockless design language - ilia greenblatClockless design language - ilia greenblat
Clockless design language - ilia greenblatchiportal
 

Tendances (20)

[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Checking VirtualDub
Checking VirtualDubChecking VirtualDub
Checking VirtualDub
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Jvm internals 2015 - CorkJUG
Jvm internals 2015 - CorkJUGJvm internals 2015 - CorkJUG
Jvm internals 2015 - CorkJUG
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
04 threads
04 threads04 threads
04 threads
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Clockless design language - ilia greenblat
Clockless design language - ilia greenblatClockless design language - ilia greenblat
Clockless design language - ilia greenblat
 

En vedette

Visualising Gargage Collection using Visual VM
Visualising Gargage Collection using Visual VMVisualising Gargage Collection using Visual VM
Visualising Gargage Collection using Visual VMLuiz Fernando Teston
 
The Content Arms Race: Why Brands Are Screwed
The Content Arms Race: Why Brands Are ScrewedThe Content Arms Race: Why Brands Are Screwed
The Content Arms Race: Why Brands Are ScrewedAndrew Grinaker
 
IBM Monitoring and Diagnostics Tools - Health Center 3.0.2
IBM Monitoring and Diagnostics Tools - Health Center 3.0.2IBM Monitoring and Diagnostics Tools - Health Center 3.0.2
IBM Monitoring and Diagnostics Tools - Health Center 3.0.2Chris Bailey
 
Predicate | Our Capabilities: The Predicate Approach to Content Strategy
Predicate | Our Capabilities: The Predicate Approach to Content StrategyPredicate | Our Capabilities: The Predicate Approach to Content Strategy
Predicate | Our Capabilities: The Predicate Approach to Content StrategyBucket Holdings
 
Java gc
Java gcJava gc
Java gcNiit
 
Java GC - Pause tuning
Java GC - Pause tuningJava GC - Pause tuning
Java GC - Pause tuningekino
 
Java Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyJava Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyDhanu Gupta
 
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Anna Shymchenko
 
Java Memory Consistency Model - concepts and context
Java Memory Consistency Model - concepts and contextJava Memory Consistency Model - concepts and context
Java Memory Consistency Model - concepts and contextTomek Borek
 
Java gc and JVM optimization
Java gc  and JVM optimizationJava gc  and JVM optimization
Java gc and JVM optimizationRajan Jethva
 
What you need to know about GC
What you need to know about GCWhat you need to know about GC
What you need to know about GCKelum Senanayake
 
Tuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issuesTuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issuesSergey Podolsky
 
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 PresentationGC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 PresentationLudovic Poitou
 

En vedette (20)

Visualising Gargage Collection using Visual VM
Visualising Gargage Collection using Visual VMVisualising Gargage Collection using Visual VM
Visualising Gargage Collection using Visual VM
 
The Content Arms Race: Why Brands Are Screwed
The Content Arms Race: Why Brands Are ScrewedThe Content Arms Race: Why Brands Are Screwed
The Content Arms Race: Why Brands Are Screwed
 
IBM Monitoring and Diagnostics Tools - Health Center 3.0.2
IBM Monitoring and Diagnostics Tools - Health Center 3.0.2IBM Monitoring and Diagnostics Tools - Health Center 3.0.2
IBM Monitoring and Diagnostics Tools - Health Center 3.0.2
 
Predicate | Our Capabilities: The Predicate Approach to Content Strategy
Predicate | Our Capabilities: The Predicate Approach to Content StrategyPredicate | Our Capabilities: The Predicate Approach to Content Strategy
Predicate | Our Capabilities: The Predicate Approach to Content Strategy
 
Java gc
Java gcJava gc
Java gc
 
[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
 
Java GC - Pause tuning
Java GC - Pause tuningJava GC - Pause tuning
Java GC - Pause tuning
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Java Garbage Collection(GC)- Study
Java Garbage Collection(GC)- StudyJava Garbage Collection(GC)- Study
Java Garbage Collection(GC)- Study
 
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Java Memory Consistency Model - concepts and context
Java Memory Consistency Model - concepts and contextJava Memory Consistency Model - concepts and context
Java Memory Consistency Model - concepts and context
 
Java gc and JVM optimization
Java gc  and JVM optimizationJava gc  and JVM optimization
Java gc and JVM optimization
 
What you need to know about GC
What you need to know about GCWhat you need to know about GC
What you need to know about GC
 
Java GC, Off-heap workshop
Java GC, Off-heap workshopJava GC, Off-heap workshop
Java GC, Off-heap workshop
 
How long can you afford to Stop The World?
How long can you afford to Stop The World?How long can you afford to Stop The World?
How long can you afford to Stop The World?
 
JVM及其调优
JVM及其调优JVM及其调优
JVM及其调优
 
Tuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issuesTuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issues
 
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 PresentationGC Tuning in the HotSpot Java VM - a FISL 10 Presentation
GC Tuning in the HotSpot Java VM - a FISL 10 Presentation
 

Similaire à Threads and Java Memory Model Explained

Jvm performance tuning
Jvm performance tuningJvm performance tuning
Jvm performance tuningIgor Igoroshka
 
Real World Lessons On The Anti-Patterns of Node.JS
Real World Lessons On The Anti-Patterns of Node.JSReal World Lessons On The Anti-Patterns of Node.JS
Real World Lessons On The Anti-Patterns of Node.JSBen Hall
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in PythonMosky Liu
 
Akka cluster in-use
Akka cluster in-useAkka cluster in-use
Akka cluster in-useKnoldus Inc.
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]RootedCON
 
Node.js Anti Patterns
Node.js Anti PatternsNode.js Anti Patterns
Node.js Anti PatternsBen Hall
 
One Container, Two Container, Three Containers, Four
One Container, Two Container, Three Containers, FourOne Container, Two Container, Three Containers, Four
One Container, Two Container, Three Containers, FourAshley Roach
 
Puppet Camp Berlin 2015: Rapid testing Setups for Puppet
Puppet Camp Berlin 2015: Rapid testing Setups for PuppetPuppet Camp Berlin 2015: Rapid testing Setups for Puppet
Puppet Camp Berlin 2015: Rapid testing Setups for PuppetPuppet
 
Puppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for Puppet
Puppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for PuppetPuppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for Puppet
Puppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for PuppetNETWAYS
 
How to make_your_first_robot
How to make_your_first_robotHow to make_your_first_robot
How to make_your_first_robotLanka Praneeth
 
Monkeybars in the Manor
Monkeybars in the ManorMonkeybars in the Manor
Monkeybars in the Manormartinbtt
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Sachintha Gunasena
 
How to make your first robot report
How to make your first robot reportHow to make your first robot report
How to make your first robot reportRamki M
 
2009 Eclipse Con
2009 Eclipse Con2009 Eclipse Con
2009 Eclipse Conguest29922
 

Similaire à Threads and Java Memory Model Explained (20)

Concurrency
ConcurrencyConcurrency
Concurrency
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Jvm performance tuning
Jvm performance tuningJvm performance tuning
Jvm performance tuning
 
Real World Lessons On The Anti-Patterns of Node.JS
Real World Lessons On The Anti-Patterns of Node.JSReal World Lessons On The Anti-Patterns of Node.JS
Real World Lessons On The Anti-Patterns of Node.JS
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
 
Akka cluster in-use
Akka cluster in-useAkka cluster in-use
Akka cluster in-use
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]
 
Node.js Anti Patterns
Node.js Anti PatternsNode.js Anti Patterns
Node.js Anti Patterns
 
One Container, Two Container, Three Containers, Four
One Container, Two Container, Three Containers, FourOne Container, Two Container, Three Containers, Four
One Container, Two Container, Three Containers, Four
 
Embracing Events
Embracing EventsEmbracing Events
Embracing Events
 
Puppet Camp Berlin 2015: Rapid testing Setups for Puppet
Puppet Camp Berlin 2015: Rapid testing Setups for PuppetPuppet Camp Berlin 2015: Rapid testing Setups for Puppet
Puppet Camp Berlin 2015: Rapid testing Setups for Puppet
 
Puppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for Puppet
Puppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for PuppetPuppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for Puppet
Puppet Camp Berlin 2015: Felix Frank | Rapid Testing Setups for Puppet
 
How to make_your_first_robot
How to make_your_first_robotHow to make_your_first_robot
How to make_your_first_robot
 
Monkeybars in the Manor
Monkeybars in the ManorMonkeybars in the Manor
Monkeybars in the Manor
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
How to make your first robot report
How to make your first robot reportHow to make your first robot report
How to make your first robot report
 
2009 Eclipse Con
2009 Eclipse Con2009 Eclipse Con
2009 Eclipse Con
 

Dernier

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
🐬 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
 
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 Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
[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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Dernier (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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 Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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...
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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...
 
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
 
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?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Threads and Java Memory Model Explained

  • 1. THREADS AND JAVA MEMORY MODEL EXPLAINED LUIZ TESTON, WWW.FRACTA.CC
  • 2. SOME QUOTES I HEARD IN MY CAREER
  • 3. “DEAD LOCK ON 300 THREADS. CAN ANYBODY HELP ME?” Soft real time developer
  • 4. “IN PARALLEL IT IS WORSE.” // GLOBAL LOCK ON A HUGE GRAPH Myself struggling to fix a performance issue
  • 5. “LET’S NOT USE THREADS, IT ALWAYS GIVES US TROUBLE.” Architect with 15 years of experience
  • 6. “MY CODE WORKS.” // NO SYNCHRONISATION, ONLY THREADS Lead Programmer
  • 7. DOING MANY THINGS AT ONCE? A FEW THINGS YOU SHOULD KNOW…
  • 9. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 10. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 11. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 12. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 14. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 16. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE X
  • 17. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 18. DEFINITION ON YOUR FAVOURITE SEARCH ENGINE
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 32. RACE CONDITION ▸ definition: shared resources may get used “at the same time” by different threads, resulting in a invalid state. ▸ motivation: any need of concurrent or parallel processing. ▸ how to avoid: usage of some mechanism to ensure resources are used by only one thread at a time or even share nothing.
  • 33. thread 1 thread 2 VAR=0
  • 34. thread 1 thread 2 VAR=0 VAR++ VAR++
  • 35. thread 1 thread 2 VAR=0 VAR++ VAR++ VAR=1 Clearly not the expected result. There are code in production working with those errors for years without people realising it. VAR WAS NOT SYNCHRONISED PROPERLY
  • 36. AVOIDING OR FIXING THIS RACE CONDITION ▸ let the database deal with it (just kidding, but sadly it seems to be the standard way of doing it). ▸ correct synchronisation by using locks. ▸ usage of concurrent classes, such as AtomicLong. ▸ one counter per thread (summing them still requires synchronisation). ▸ share nothing. ▸ any other suggestion?
  • 37. thread 1 thread 2 VAR=0LOCK
  • 38. thread 1 thread 2 VAR=0LOCK LOCK VAR++ WAITING LOCK
  • 39. thread 1 thread 2 VAR=0LOCK VAR++ LOCK VAR++
  • 40. thread 1 thread 2 VAR=0LOCK VAR++ VAR++ VAR=2 The result was as expected, but there was a penalty in the time it took to perform both operations. In order to minimise it avoid sharing in the first place. VAR WAS PROPERLY SYNCHRONISED
  • 41. READS ALSO NEEDS SYNCHRONISATION // COMMON MISTAKE IS ONLY // SYNCHRONISE WRITES.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47. LESSONS ▸ Synchronise properly. High level APIs are easier not to mess with. java.util.concurrent excels at that. ▸ The optimal number of threads is usually twice the number of cores: Runtime.getRuntime().availableProcessors() * 2; ▸ Measure and stress. It is not easy to see synchronisation issues, since the behaviour varies depending on machine, operation system, etc. They usually don’t show while debugging.
  • 49. DEAD LOCKS ▸ what it is: threads holding and waiting each other locks. ▸ motivation: global lock leads to global contention and slow code. Use of more than one fine grained lock at the same time in more than one thread in a unpredictable way is the real problem. ▸ how to avoid: ensure same locking order or review synchronisation strategy (functional approach, atomic classes, high level APIs, concurrent collections, share nothing, etc).
  • 50. thread 1 thread 2 AB Two threads have access to resources protected by two distinct locks: A and B. Green means available, yellow means waiting and red means locked. Two scenarios are going to be presented: Threads acquiring the locks in the same order, and in different order.
  • 51. thread 1 thread 2 B A First thread acquires lock A.
  • 52. thread 1 thread 2 B A A Second thread tries to acquire the same lock. Since it is in use, it will wait until lock A is available.
  • 53. thread 1 thread 2 A A B Meanwhile the first thread acquires lock B. The second thread is still waiting for lock A.
  • 54. thread 1 thread 2 B A A The first thread releases lock B. The second thread is still waiting for lock A.
  • 55. thread 1 thread 2 AB A Then the lock A is finally released. The second thread is finally able to use it.
  • 56. thread 1 thread 2 B A It acquires lock A.
  • 57. thread 1 thread 2 A B Then it acquires lock B.
  • 58. thread 1 thread 2 B A Lock B is released.
  • 59. thread 1 thread 2 AB Then lock A is released. No synchronisation problems has happened and no locked resources where harmed in this execution. Some contention has happened, but they where temporary. EVERYTHING WAS FINE.
  • 60. thread 1 thread 2 AB NOW SOMETHING DIFFERENT
  • 61. thread 1 thread 2 B A The first thread acquires lock A.
  • 62. thread 1 thread 2 A B And the second thread acquires lock B.
  • 63. thread 1 thread 2 A B B The first thread tries to acquire lock B. Since it is busy, it will wait for it.
  • 64. thread 1 thread 2 A B B A And the second thread tries to acquire lock A. Since it is busy, it will wait for it.
  • 65. thread 1 thread 2 A B B A What did the different order of lock acquisition cause? Keep in mind locks can be acquired internally by APIs, by using the synchronised keyword, by doing IO. It is almost impossible to keep track of all the locks in a huge application stack. DEAD LOCK IS SET.
  • 66.
  • 67.
  • 68. LESSONS ▸ If sharing data between threads, synchronise properly and measure and stress (same as before). ▸ Keep in mind some dead locks keeps latent and may happen only in unusual situations (such as unusual high peak load). ▸ The best approach is to minimise sharing data, having isolated threads working independently. ▸ There are frameworks that suits better than using threads manually. Consider those, such as Akka, Disruptor, etc.
  • 69. QUESTIONS? THANKS FOR YOUR TIME! ▸ https://www.cs.umd.edu/~pugh/java/memoryModel/ jsr-133-faq.html ▸ http://docs.oracle.com/javase/specs/ ▸ fotos: Dani Teston