SlideShare a Scribd company logo
1 of 9
Download to read offline
Synchronize access to shared
mutable data
1
An important fact about mutable data and
concurrency in Java
• An update on mutable data made by one thread may not be visible by
other threads unless an appropriate synchronization is used.
• Such unsynchronized shared mutable data can cause nasty problems.
2
Example: a thread that never sees an update
3
class ThisNeverFinishesOnMyLaptop {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread backgroundThread = new Thread(() -> {
while (true) { // wait until the counter gets incremented
if (counter.getCount() != 0) break; // this never breaks; it becomes an infinite loop
}
System.out.println("Finished");
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
counter.increment();
}
}
class Counter {
int count = 0; // this is mutable data
int getCount() { return count; }
int increment() { return ++count; }
}
Code based on the example from Effective Java, 3rd edition p.312
Synchronization with synchronized blocks
4
class NowItFinishesOnMyLaptop {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Object lock = new Object();
Thread backgroundThread = new Thread(() -> {
while (true) { // wait until the counter gets incremented
synchronized (lock) {
if (counter.getCount() != 0) break; //now it works
}
}
System.out.println("Finished");
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
synchronized (lock) {
counter.increment();
}
}
}
Synchronization with volatile
5
class ThisAlsoFinishesOnMyLaptop {
public static void main(String[] args) throws InterruptedException {
VolatileCounter counter = new VolatileCounter();
Thread backgroundThread = new Thread(() -> {
while (true) { // wait until the counter gets incremented
if (counter.getCount() != 0) break; //now it works too
}
System.out.println("Finished");
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
counter.increment();
}
}
class VolatileCounter {
volatile int count = 0;
int getCount() { return count; }
int increment() { return ++count; }
}
A limitation of volatile: it doesn’t guarantee
atomicity
6
class IncrementByMultipleThreads {
public static void main(String[] args) {
VolatileCounter counter = new VolatileCounter();
Set<Integer> ints = Collections.synchronizedSet(new HashSet<>());
Runnable incrementer = () -> {
while (true) {
int increment = counter.increment();
boolean added = ints.add(increment);
if (!added) System.out.println("duplicate number detected");//volatile doesn’t prevent this
}
};
Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer);
t1.start(); t2.start(); t3.start();
}
}
Synchronization with synchronized blocks
guarantees exclusive code execution
7
class IncrementByMultipleThreadsWithLock {
public static void main(String[] args) {
Counter counter = new Counter();
Object lock = new Object();
Set<Integer> ints = Collections.synchronizedSet(new HashSet<>());
Runnable incrementer = () -> {
while (true) {
int increment;
synchronized (lock) {
increment = counter.increment();
}
boolean added = ints.add(increment);
if (!added) System.out.println("duplicate number detected"); //this doesn’t happen anymore
}
};
Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer);
t1.start(); t2.start(); t3.start();
}
}
Which classes in JDK need a synchronization
in concurrent use cases?
• HashMap
• It can trigger an infinite loop in some cases, which is extremely dangerous.
• https://mailinator.blogspot.com/2009/06/beautiful-race-condition.html
• Thread-safe equivalent: ConcurrentHashMap
• ArrayList
• Thread-safe equivalent: CopyOnWriteArrayList
• SimpleDateFormat
• Oftentimes it’s stored in a public static final field; dangerous
• Thread-safe equivalent: DateTimeFormatter
• DecimalFormat, MessageFormat, etc.
• Many more
8
Note: Just putting volatile doesn’t make those classes thread-safe.
Conclusion
• We have discussed:
• Why we need to synchronize shared mutable data
• How we can do that
• What happens when we fail to do that
• The consequences of missing synchronization can be horrible:
• Triggering an infinite loop
• Getting an invalid result or a mysterious exception
• Any sort of totally unpredictable chaos
• Minimize mutability. Immutable data is always thread-safe.
• Further reading: Java Concurrency in Practice
9

More Related Content

Similar to Synchronize access to shared mutable data

Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
rahulrevo
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
mail931892
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
Devnology
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
kostikjaylonshaewe47
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
akkhan101
 

Similar to Synchronize access to shared mutable data (20)

Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Thread
ThreadThread
Thread
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
 
delegates
delegatesdelegates
delegates
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"
 
State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net Performance
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
 

More from Kohei Nozaki (6)

The State Pattern
The State PatternThe State Pattern
The State Pattern
 
The Singleton Pattern In Java
The Singleton Pattern In JavaThe Singleton Pattern In Java
The Singleton Pattern In Java
 
Favor composition over inheritance
Favor composition over inheritanceFavor composition over inheritance
Favor composition over inheritance
 
Java Generics wildcards
Java Generics wildcardsJava Generics wildcards
Java Generics wildcards
 
JUnit and Mockito tips
JUnit and Mockito tipsJUnit and Mockito tips
JUnit and Mockito tips
 
Overview of Java EE
Overview of Java EEOverview of Java EE
Overview of Java EE
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Synchronize access to shared mutable data

  • 1. Synchronize access to shared mutable data 1
  • 2. An important fact about mutable data and concurrency in Java • An update on mutable data made by one thread may not be visible by other threads unless an appropriate synchronization is used. • Such unsynchronized shared mutable data can cause nasty problems. 2
  • 3. Example: a thread that never sees an update 3 class ThisNeverFinishesOnMyLaptop { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Thread backgroundThread = new Thread(() -> { while (true) { // wait until the counter gets incremented if (counter.getCount() != 0) break; // this never breaks; it becomes an infinite loop } System.out.println("Finished"); }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); counter.increment(); } } class Counter { int count = 0; // this is mutable data int getCount() { return count; } int increment() { return ++count; } } Code based on the example from Effective Java, 3rd edition p.312
  • 4. Synchronization with synchronized blocks 4 class NowItFinishesOnMyLaptop { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Object lock = new Object(); Thread backgroundThread = new Thread(() -> { while (true) { // wait until the counter gets incremented synchronized (lock) { if (counter.getCount() != 0) break; //now it works } } System.out.println("Finished"); }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); synchronized (lock) { counter.increment(); } } }
  • 5. Synchronization with volatile 5 class ThisAlsoFinishesOnMyLaptop { public static void main(String[] args) throws InterruptedException { VolatileCounter counter = new VolatileCounter(); Thread backgroundThread = new Thread(() -> { while (true) { // wait until the counter gets incremented if (counter.getCount() != 0) break; //now it works too } System.out.println("Finished"); }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); counter.increment(); } } class VolatileCounter { volatile int count = 0; int getCount() { return count; } int increment() { return ++count; } }
  • 6. A limitation of volatile: it doesn’t guarantee atomicity 6 class IncrementByMultipleThreads { public static void main(String[] args) { VolatileCounter counter = new VolatileCounter(); Set<Integer> ints = Collections.synchronizedSet(new HashSet<>()); Runnable incrementer = () -> { while (true) { int increment = counter.increment(); boolean added = ints.add(increment); if (!added) System.out.println("duplicate number detected");//volatile doesn’t prevent this } }; Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer); t1.start(); t2.start(); t3.start(); } }
  • 7. Synchronization with synchronized blocks guarantees exclusive code execution 7 class IncrementByMultipleThreadsWithLock { public static void main(String[] args) { Counter counter = new Counter(); Object lock = new Object(); Set<Integer> ints = Collections.synchronizedSet(new HashSet<>()); Runnable incrementer = () -> { while (true) { int increment; synchronized (lock) { increment = counter.increment(); } boolean added = ints.add(increment); if (!added) System.out.println("duplicate number detected"); //this doesn’t happen anymore } }; Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer); t1.start(); t2.start(); t3.start(); } }
  • 8. Which classes in JDK need a synchronization in concurrent use cases? • HashMap • It can trigger an infinite loop in some cases, which is extremely dangerous. • https://mailinator.blogspot.com/2009/06/beautiful-race-condition.html • Thread-safe equivalent: ConcurrentHashMap • ArrayList • Thread-safe equivalent: CopyOnWriteArrayList • SimpleDateFormat • Oftentimes it’s stored in a public static final field; dangerous • Thread-safe equivalent: DateTimeFormatter • DecimalFormat, MessageFormat, etc. • Many more 8 Note: Just putting volatile doesn’t make those classes thread-safe.
  • 9. Conclusion • We have discussed: • Why we need to synchronize shared mutable data • How we can do that • What happens when we fail to do that • The consequences of missing synchronization can be horrible: • Triggering an infinite loop • Getting an invalid result or a mysterious exception • Any sort of totally unpredictable chaos • Minimize mutability. Immutable data is always thread-safe. • Further reading: Java Concurrency in Practice 9