SlideShare a Scribd company logo
1 of 29
Download to read offline
2015/04/28 讀書會分享
Effective Java
摘選條目分享 3
- Concurrency
Kane
大綱
Concurrency issues?
atomic
volatile
synchronized
常用類別
wait / notify
Thread Safety
You should already know ...
http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread
You should already know ...
http://nerds.weddingpartyapp.com/tech/2014/06/20/primer-threading-handlers-android/
You should already know...
https://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html
Concurrency issues
What is the most frequent concurrency issue you've encountered in Java?
http://stackoverflow.com/questions/461896/what-is-the-most-frequent-
concurrency-issue-youve-encountered-in-java
Problem
class MyThread extends Thread {
private boolean stop = false;
public void run() {
while(!stop) {
doSomeWork();
}
}
public void setStop() {
this.stop = true;
}
調用了setStop(),
卻可能仍然不會停下。
暫存
http://javarevisited.blogspot.tw/2011/06/volatile-keyword-java-example-tutorial.html
volatile
http://www.slideshare.net/caroljmcdonald/java-concurrency-memory-model-and-trends-4961797
volatile 注意事項
對該變數的所有操作皆為原子操作?
http://stackoverflow.com/questions/3519664/difference-between-volatile-and-synchronized-in-java
考慮以下這段程式碼
public void updateCounter() {
if (counter == 1000) {
counter = 0;
} else {
counter++;
}
}
考慮以下這段程式碼
public void updateCounter() {
if (counter == 1000) {
counter = 0;
} else {
counter++;
}
}
從 main memory 讀取至 cache
在 cache 中更新值
在某個時機點寫回 main memory
Case: Two threads
if (counter == 1000) {
counter = 0;
} else {
counter++;
}
if (counter == 1000) {
counter = 0;
} else {
counter++;
}
thread 1 thread 2
atomic
● 不可切割
● a++; 讀取 a
更新 a
synchronized
http://www.ibm.com/developerworks/library/j-jtp03304/
waiting for M’s lock
object locking / monitor
https://www.artima.com/insidejvm/ed2/threadsynchP.html
synchronized 注意事項
● 避免調用外部方法
i.e. Template Method Pattern, callback, sub-class’s
method, ...
● 重入 (reentrant)
常用類別 - 資料、容器
AtomicInteger, AtomicLong …
CopyOnWriteArrayList
ConcurrentHashMap
...
常用類別 - 資料、容器
AtomicInteger, AtomicLong …
CopyOnWriteArrayList
ConcurrentHashMap
...
putIfAbsent(k, v)
-----------------------------
if (containsKey(k)) {
return put(k, v);
} else {
return get(k);
}
常用類別 - 控制
Executor, ExecutorService, …
CountDownLatch
Semaphore
CyclicBarrier
常用類別 - 控制
Executor, ExecutorService, …
CountDownLatch
Semaphore
CyclicBarrier
更方便控制的 thread pool
常用類別 - 控制
Executor, ExecutorService, …
CountDownLatch
Semaphore
CyclicBarrier
等到扣完才動
同時間只有 n 個能進入
等到有 n 個到達 await() 後才動
wait / notify
1. 應優先使用 java.util.concurrent 提供的類別
2. wait 必在 loop 中使用
3. 優先考慮 notifyAll
https://codexplo.wordpress.com/2012/10/20/state-diagram-of-java-thread/
WHY: wait 必在 loop 中使用
1. notify 已經做了,先檢查條件可免 wait
2. 別人做了 notifyAll
3. spurious wakeup
synchronized (obj) {
while (<需等待的條件>) {
obj.wait();
}
}
spurious wake
scheduler可能因為一些原因而blackout
中間可能錯失信號
故回復時會喚醒 thread,避免無限 waiting
關鍵字:POSIX Threads, Windows API,
pthread_cond_wait, futex
優先考慮 notifyAll
1. 避免沒有收到 notify 的情況
2. 保護:wait 在 loop 中
Thread Safety
1. immutable 不需要外部同步,因為instance狀態不變
2. unconditionally thread-safe 不需要外部同步
3. conditionally thread-safe 有些條件下必須使用外部同步
4. not thread-safe 使用者要自己控制同步
5. thread-hostile 就算都做了外部同步,也不行
Q&A

More Related Content

Similar to Effective java 摘選條目分享 3 - concurrency

201 core java interview questions oo ps interview questions - javatpoint
201 core java interview questions   oo ps interview questions - javatpoint201 core java interview questions   oo ps interview questions - javatpoint
201 core java interview questions oo ps interview questions - javatpointravi tyagi
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Edureka!
 
Java online training, java training in bangalore, java training
Java online training, java training in bangalore, java trainingJava online training, java training in bangalore, java training
Java online training, java training in bangalore, java trainingVyshnavi Reddy
 
Debugging java deployments_2
Debugging java deployments_2Debugging java deployments_2
Debugging java deployments_2Rohit Kelapure
 
Flavors of Concurrency in Java
Flavors of Concurrency in JavaFlavors of Concurrency in Java
Flavors of Concurrency in JavaJavaDayUA
 
Multithreading in Java.pdf
Multithreading in Java.pdfMultithreading in Java.pdf
Multithreading in Java.pdfKevLaine
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and GotchasConcurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchasamccullo
 
Questions of java
Questions of javaQuestions of java
Questions of javaWaseem Wasi
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
 
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...David Buck
 

Similar to Effective java 摘選條目分享 3 - concurrency (20)

201 core java interview questions oo ps interview questions - javatpoint
201 core java interview questions   oo ps interview questions - javatpoint201 core java interview questions   oo ps interview questions - javatpoint
201 core java interview questions oo ps interview questions - javatpoint
 
Le Tour de xUnit
Le Tour de xUnitLe Tour de xUnit
Le Tour de xUnit
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
 
Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
 
Java online training, java training in bangalore, java training
Java online training, java training in bangalore, java trainingJava online training, java training in bangalore, java training
Java online training, java training in bangalore, java training
 
Debugging java deployments_2
Debugging java deployments_2Debugging java deployments_2
Debugging java deployments_2
 
Flavors of Concurrency in Java
Flavors of Concurrency in JavaFlavors of Concurrency in Java
Flavors of Concurrency in Java
 
Multithreading in Java.pdf
Multithreading in Java.pdfMultithreading in Java.pdf
Multithreading in Java.pdf
 
Troubleshooting Java HotSpot VM
Troubleshooting Java HotSpot VMTroubleshooting Java HotSpot VM
Troubleshooting Java HotSpot VM
 
JAVA Training in Bangalore
JAVA Training in BangaloreJAVA Training in Bangalore
JAVA Training in Bangalore
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
 
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and GotchasConcurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchas
 
Questions of java
Questions of javaQuestions of java
Questions of java
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
 

Recently uploaded

Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 

Recently uploaded (20)

Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 

Effective java 摘選條目分享 3 - concurrency