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

PDF
Real time stream processing presentation at General Assemb.ly
PPTX
Database connectivity in python
PDF
Cryptographic Hash Function using Cellular Automata
PPTX
Michael Häusler – Everyday flink
PDF
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015
PPT
computer notes - Data Structures - 35
PPT
Computer notes - Hashing
PPTX
Reactive Programming no Android
Real time stream processing presentation at General Assemb.ly
Database connectivity in python
Cryptographic Hash Function using Cellular Automata
Michael Häusler – Everyday flink
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015
computer notes - Data Structures - 35
Computer notes - Hashing
Reactive Programming no Android

Similar to Synchronize access to shared mutable data (20)

PDF
Study effective java item 78 synchronize access to mutable data
PPTX
Java concurrency
PPTX
Concurrency
PDF
Java Concurrency by Example
PDF
Java Concurrency by Example
PDF
Concurrent programming without synchronization
PDF
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
PPTX
Java concurrency
PPT
Java concurrency
PDF
Java 8 - Stamped Lock
PPTX
Effective java - concurrency
PPT
Concurrency Patterns
PDF
jvm/java - towards lock-free concurrency
PPTX
Concurrency
PDF
Non-blocking synchronization — what is it and why we (don't?) need it
PDF
Concurrency gotchas
PPTX
Николай Папирный Тема: "Java memory model для простых смертных"
PPTX
Concurrency in Java
PDF
Concurrency
PDF
Java Concurrency Gotchas
Study effective java item 78 synchronize access to mutable data
Java concurrency
Concurrency
Java Concurrency by Example
Java Concurrency by Example
Concurrent programming without synchronization
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
Java concurrency
Java concurrency
Java 8 - Stamped Lock
Effective java - concurrency
Concurrency Patterns
jvm/java - towards lock-free concurrency
Concurrency
Non-blocking synchronization — what is it and why we (don't?) need it
Concurrency gotchas
Николай Папирный Тема: "Java memory model для простых смертных"
Concurrency in Java
Concurrency
Java Concurrency Gotchas
Ad

More from Kohei Nozaki (6)

PDF
The State Pattern
PDF
The Singleton Pattern In Java
PDF
Favor composition over inheritance
PDF
Java Generics wildcards
PDF
JUnit and Mockito tips
PDF
Overview of Java EE
The State Pattern
The Singleton Pattern In Java
Favor composition over inheritance
Java Generics wildcards
JUnit and Mockito tips
Overview of Java EE
Ad

Recently uploaded (20)

PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Nekopoi APK 2025 free lastest update
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
history of c programming in notes for students .pptx
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
System and Network Administraation Chapter 3
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Design an Analysis of Algorithms II-SECS-1021-03
VVF-Customer-Presentation2025-Ver1.9.pptx
Nekopoi APK 2025 free lastest update
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
wealthsignaloriginal-com-DS-text-... (1).pdf
Navsoft: AI-Powered Business Solutions & Custom Software Development
Understanding Forklifts - TECH EHS Solution
Reimagine Home Health with the Power of Agentic AI​
PTS Company Brochure 2025 (1).pdf.......
How to Migrate SBCGlobal Email to Yahoo Easily
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
history of c programming in notes for students .pptx
CHAPTER 2 - PM Management and IT Context
Adobe Illustrator 28.6 Crack My Vision of Vector Design
System and Network Administraation Chapter 3
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
L1 - Introduction to python Backend.pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...

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