SlideShare a Scribd company logo
Concurrency Errors
in Java
What Is a Concurrency Error?
And Why You Should Care About Them
What Is a Concurrency Error?
A concurrency error is the result
of incorrect synchronization
safeguards in
multi-threaded software. Typical
concurrency errors include race
conditions and starvation.
Why You Should Care
Consequences to users:
• Data corruption
• Security vulnerabilities
• Incorrect behavior
• Denial of service
Consequences to developers:
• Time consuming to find, even with a debugger
• Difficult to test for
• Can reduce reliability of the testing suite by interrupting
test runs
Java is a modern language with
synchronization primitives to
enforce safe concurrency models.
Does that mean that concurrency
errors are easy to avoid in Java?
Question:
Answer:
No!
The concurrency primitives help you implement a
well-designed concurrency model. But:
• You still need to design the concurrency model
• Concurrency primitives applied incorrectly do not protect
you from problems
• It’s easy to apply concurrency primitives incorrectly
• Bottom line: concurrency is tricky, even in Java!
Consider this Code Snippet*
Note:
• msg is read from the session on line 64
• msg is removed from the session on line 71
• This code is not enclosed in a “synchronized” block
• Other threads may read/update the session
* From an open source project
Consider this case:
1. You read msg (line 64)
2. Another thread changes the status message
3. You delete the status message (line 71)
You just lost the other thread’s status message!
Problem: You Might Lose Status Messages in
Your App
To Avoid the Problem:
You need to handle the read/delete atomically.
Maybe something like this:
synchronized(this) { // or add “synchronized” to the method
msg = (String)req.getSession().getAttribute(STATUS_MESSAGE);
if (msg != null)
{
// Move pw.printLn() calls outside the sync. block
req.getSession().removeAttribute(STATUS_MESSAGE);
}
}
We do an atomic read/delete, so things will work
correctly, right?
No!
(Remember, concurrency is tricky!)
To Avoid the Problem:
You need to handle the read/delete atomically.
While holding an appropriate lock
synchronized(this) { // or add “synchronized” to the method
msg = (String)req.getSession().getAttribute(STATUS_MESSAGE);
if (msg != null)
{
// Move pw.printLn() calls outside the sync. block
req.getSession().removeAttribute(STATUS_MESSAGE);
}
}
Because we’re locking on this, other threads will be able to
use the session while we do our work—it’s not really atomic!
We need to lock on a shared object, like the session, instead.
But locking on the session has its own problems!
(Remember, concurrency is tricky!)
To Avoid the Problem:
You need to handle the read/delete atomically.
While holding an appropriate lock
// You need to define session_lock in an appropriate scope
// and ensure other threads use that same lock
synchronized(session_lock) {
msg = (String)req.getSession().getAttribute(STATUS_MESSAGE);
if (msg != null)
{
// Move pw.printLn() calls outside the sync. block
req.getSession().removeAttribute(STATUS_MESSAGE);
}
}
By having all threads lock on the same object, you can ensure
that the status message is managed safely.
It can be challenging to implement the lock in the proper
scope—you often have to choose between correctness and
performance.
In Short…
1. Remain vigilant about concurrency errors
• Understand how objects are shared between threads
• Be certain that you are locking on appropriate objects
• Be careful to handle exceptional cases, too!
2. Use tools to identify cases that you miss
• Static analysis (often available in IDE, too!)
• Dynamic analysis
3. Enjoy the extra time you’ve freed up 
demo
http://www.coverity.com/request-a-free-trial.html
Want to learn more about how Coverity
can help you write better code?
Request a free trial:
Copyright 2013 Coverity, Inc.

More Related Content

PPTX
Resource Leaks in Java
PPTX
OSS Java Analysis - What You Might Be Missing
PPTX
Adopting Agile
PPTX
Static Analysis Primer
PPTX
Finding Defects in C#: Coverity vs. FxCop
PPTX
DevBeat 2013 - Developer-first Security
ODP
@LinkingNote annotation in YATSPEC
PPTX
UK star ultimate testing survival
Resource Leaks in Java
OSS Java Analysis - What You Might Be Missing
Adopting Agile
Static Analysis Primer
Finding Defects in C#: Coverity vs. FxCop
DevBeat 2013 - Developer-first Security
@LinkingNote annotation in YATSPEC
UK star ultimate testing survival

What's hot (20)

PPTX
Bug prediction based on your code history
PPTX
Is Groovy better for testing than Java?
PDF
TDD — Are you sure you properly test code?
PDF
10 things you didn't know about RxSwift
PPTX
Google, quality and you
PDF
Effective debugging
PPTX
How to improve code quality for iOS apps?
PDF
Staying Ahead of the Curve
PDF
[FullStack NYC 2019] Effective Unit Tests for JavaScript
PDF
Code Review Matters and Manners
PPTX
Common mistakes in tdd can you guess
PPTX
Selenium Camp 2016 - Effective UI tests scaling on Java
PDF
Level Up Your Automated Tests
PDF
Performant Django - Ara Anjargolian
PPTX
Level Up Your Automated Tests
PPTX
PHPUnit - Unit testing
PPTX
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
PPTX
The Engineer's Playbook: Starting a New Role
PDF
Testing without assertions - #HUSTEF2019
PDF
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
Bug prediction based on your code history
Is Groovy better for testing than Java?
TDD — Are you sure you properly test code?
10 things you didn't know about RxSwift
Google, quality and you
Effective debugging
How to improve code quality for iOS apps?
Staying Ahead of the Curve
[FullStack NYC 2019] Effective Unit Tests for JavaScript
Code Review Matters and Manners
Common mistakes in tdd can you guess
Selenium Camp 2016 - Effective UI tests scaling on Java
Level Up Your Automated Tests
Performant Django - Ara Anjargolian
Level Up Your Automated Tests
PHPUnit - Unit testing
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
The Engineer's Playbook: Starting a New Role
Testing without assertions - #HUSTEF2019
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
Ad

Viewers also liked (20)

PDF
PDF
Render thead of hwui
PPT
Android图形系统简介
PPTX
The Landbank's Role in Driving Redevelopment, UC DAAP by Chris Recht
PPT
Core & advanced java classes in mumbai
DOCX
SAP_Business_Object_Professional
PDF
PaaSing a Java EE 6 Application at Geecon 2012
PDF
Global leader in real-time clearing
PPTX
Learn advanced java programming
PPT
Developing With JAAS
PDF
7 Common mistakes in Go and when to avoid them
PPT
03 stacks and_queues_using_arrays
PDF
A Short Intorduction to JasperReports
PDF
The Android graphics path, in depth
PDF
RESTful Web services using JAX-RS
PDF
Introduction to Jasper Reports
ODP
Japer Reports
PPT
Architecture of message oriented middleware
PDF
MOM - Message Oriented Middleware
PPTX
Rest API Security
Render thead of hwui
Android图形系统简介
The Landbank's Role in Driving Redevelopment, UC DAAP by Chris Recht
Core & advanced java classes in mumbai
SAP_Business_Object_Professional
PaaSing a Java EE 6 Application at Geecon 2012
Global leader in real-time clearing
Learn advanced java programming
Developing With JAAS
7 Common mistakes in Go and when to avoid them
03 stacks and_queues_using_arrays
A Short Intorduction to JasperReports
The Android graphics path, in depth
RESTful Web services using JAX-RS
Introduction to Jasper Reports
Japer Reports
Architecture of message oriented middleware
MOM - Message Oriented Middleware
Rest API Security
Ad

Similar to Concurrency Errors in Java (20)

PPTX
Concurrency
PDF
Concurrency in Java
PDF
Concurrent Programming in Java
PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
PPTX
JEEConf 2017 - How to find deadlock not getting into it
PDF
Concurrency: Best Practices
PDF
Java concurrency in practice
PPTX
Concurrency
PPTX
Basics of Java Concurrency
PDF
Concurrency-5.pdf
ODP
Java Concurrency, Memory Model, and Trends
PPT
Java concurrency
ODP
Java Concurrency
PPTX
Multithreading and concurrency in android
PPTX
Java concurrency
PPTX
PPTX
Thread & concurrancy
PPTX
Java Concurrency and Asynchronous
PPTX
Concurrency - Why it's hard ?
PPT
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
Concurrency
Concurrency in Java
Concurrent Programming in Java
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
JEEConf 2017 - How to find deadlock not getting into it
Concurrency: Best Practices
Java concurrency in practice
Concurrency
Basics of Java Concurrency
Concurrency-5.pdf
Java Concurrency, Memory Model, and Trends
Java concurrency
Java Concurrency
Multithreading and concurrency in android
Java concurrency
Thread & concurrancy
Java Concurrency and Asynchronous
Concurrency - Why it's hard ?
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
Sensors and Actuators in IoT Systems using pdf
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced Soft Computing BINUS July 2025.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Understanding_Digital_Forensics_Presentation.pptx
GamePlan Trading System Review: Professional Trader's Honest Take
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
madgavkar20181017ppt McKinsey Presentation.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
The AUB Centre for AI in Media Proposal.docx
Chapter 3 Spatial Domain Image Processing.pdf

Concurrency Errors in Java

  • 2. What Is a Concurrency Error? And Why You Should Care About Them
  • 3. What Is a Concurrency Error? A concurrency error is the result of incorrect synchronization safeguards in multi-threaded software. Typical concurrency errors include race conditions and starvation.
  • 4. Why You Should Care Consequences to users: • Data corruption • Security vulnerabilities • Incorrect behavior • Denial of service Consequences to developers: • Time consuming to find, even with a debugger • Difficult to test for • Can reduce reliability of the testing suite by interrupting test runs
  • 5. Java is a modern language with synchronization primitives to enforce safe concurrency models. Does that mean that concurrency errors are easy to avoid in Java? Question:
  • 6. Answer: No! The concurrency primitives help you implement a well-designed concurrency model. But: • You still need to design the concurrency model • Concurrency primitives applied incorrectly do not protect you from problems • It’s easy to apply concurrency primitives incorrectly • Bottom line: concurrency is tricky, even in Java!
  • 7. Consider this Code Snippet* Note: • msg is read from the session on line 64 • msg is removed from the session on line 71 • This code is not enclosed in a “synchronized” block • Other threads may read/update the session * From an open source project
  • 8. Consider this case: 1. You read msg (line 64) 2. Another thread changes the status message 3. You delete the status message (line 71) You just lost the other thread’s status message! Problem: You Might Lose Status Messages in Your App
  • 9. To Avoid the Problem: You need to handle the read/delete atomically. Maybe something like this: synchronized(this) { // or add “synchronized” to the method msg = (String)req.getSession().getAttribute(STATUS_MESSAGE); if (msg != null) { // Move pw.printLn() calls outside the sync. block req.getSession().removeAttribute(STATUS_MESSAGE); } } We do an atomic read/delete, so things will work correctly, right? No! (Remember, concurrency is tricky!)
  • 10. To Avoid the Problem: You need to handle the read/delete atomically. While holding an appropriate lock synchronized(this) { // or add “synchronized” to the method msg = (String)req.getSession().getAttribute(STATUS_MESSAGE); if (msg != null) { // Move pw.printLn() calls outside the sync. block req.getSession().removeAttribute(STATUS_MESSAGE); } } Because we’re locking on this, other threads will be able to use the session while we do our work—it’s not really atomic! We need to lock on a shared object, like the session, instead. But locking on the session has its own problems! (Remember, concurrency is tricky!)
  • 11. To Avoid the Problem: You need to handle the read/delete atomically. While holding an appropriate lock // You need to define session_lock in an appropriate scope // and ensure other threads use that same lock synchronized(session_lock) { msg = (String)req.getSession().getAttribute(STATUS_MESSAGE); if (msg != null) { // Move pw.printLn() calls outside the sync. block req.getSession().removeAttribute(STATUS_MESSAGE); } } By having all threads lock on the same object, you can ensure that the status message is managed safely. It can be challenging to implement the lock in the proper scope—you often have to choose between correctness and performance.
  • 12. In Short… 1. Remain vigilant about concurrency errors • Understand how objects are shared between threads • Be certain that you are locking on appropriate objects • Be careful to handle exceptional cases, too! 2. Use tools to identify cases that you miss • Static analysis (often available in IDE, too!) • Dynamic analysis 3. Enjoy the extra time you’ve freed up 
  • 13. demo http://www.coverity.com/request-a-free-trial.html Want to learn more about how Coverity can help you write better code? Request a free trial: