SlideShare a Scribd company logo
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

Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
ishan0019
 
Thread
ThreadThread
Thread
phanleson
 
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
Fedor Lavrentyev
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
rahulrevo
 
delegates
delegatesdelegates
delegates
Owais Masood
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
Arvind Krishnaa
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
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
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
Sandeep Joshi
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
Jafar Nesargi
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
Achini Samuditha
 
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
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
Fahad Shaikh
 
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"
Yulia Tsisyk
 
State of the .Net Performance
State of the .Net PerformanceState of the .Net Performance
State of the .Net Performance
CUSTIS
 
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
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
Mahyuddin8
 

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

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

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

2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 

Recently uploaded (20)

2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 

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