How to write Thread-Safe Code in Java
source link: https://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.html#axzz8AnGJRBUm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to write Thread-Safe Code in Java
It's an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance.
How to make Thread-Safe Code in Java
Before you learn how to write a thread-safe code you need to understand what is thread-safety and there is no better way to that than looking at a non-thread-safe code. So, let's see an example of the potential, not thread-safe code, and learn how to fix that.
Example of Non-Thread-Safe Code in Java
If multiple thread call getCount() approximately same time each of these three operations may coincide or overlap with each other for example while thread 1 is updating value, thread 2 reads and still gets old value, which eventually let thread 2 override thread 1 increment and one count is lost because multiple threads called it concurrently.
How to make code Thread-Safe in Java
This is an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance.
Important points about Thread-Safety in Java
Also, JVM plays a spoiler since it can reorder code for optimization, so the code which looks sequential and runs fine in the development environment not guaranteed to run similarly in the production environment because JVM may ergonomically adjust itself as server JVM and perform more optimization and reorder which cause thread-safety issues.
Multithreading and Parallel Computing in Java
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice Course by Heinz Kabutz
- Top 50 Java Multithreading Interview Questions from last 5 years (list)
- Top 5 Courses to learn Multithreading and Concurrency in Java (courses)
- How to use Future and FutureTask in Java? (tutorial)
- Is "Java Concurrency in Practice" Still Valid in the era of Java 8? (opinion)
- How to join more than two Threads in Java? (example)
- What is the right way to stop a Thread in Java? (tutorial)
- Top 10 Courses to learn Java in-depth (courses)
- Top 5 courses to Learn Java Performance Tuning (courses)
- 10 Courses to Crack Java Interviews for Beginners (courses)
- Top 12 Java Concurrency Questions for Experienced Programmers (see here)
- Difference between multi-threading and multi-tasking in Java? (answer)
- Top 5 Books to learn Java Concurrency in-depth (books)
- What is happens-before in Java Concurrency? (answer)
- 6 Books to learn Multithreading and Concurrency in Java (books)
- 10 Advanced Core Java Courses for Experienced programmers (course)
14 comments :
Anonymous said...
Atomicity is just one way which can cause thread-safety or concurrency issue, how about visibility, ordering etc ? visibility related concurrency and thread-safety issues are more hard to debug.
vasanth said...
Super
Unknown said...
Even with volatile keyword, the threading issues are not resolved as the read-update-write issue exists between two threads even though the value of the volatile variable is read from main memory.
In my view, it only helps to give a hint to the compiler/JVM not to reorder the statements/instructions for achieving optimization.
Anonymous said...
"JVM plays a spoiler since it can reorder code for optimization, so the code which looks sequential and runs fine in development environment not guaranteed to run similarly in production environment because JVM may ergonomically adjust itself as server JVM and perform more optimization and reorder which cause thread-safety issues..."
I am experiencing this issue now a days. :(
Vivek Hingorani said...
Atomic Operation? What exactly does it mean? I was not able to understand entire code.
Can you please explain this code:
/*
* This method is thread-safe because count is incremented atomically
*/
public int getCountAtomically(){
return atomicCount.incrementAndGet();
}
}
Anbalagan Marimuthu said...
The language specification guarantees that reading or writing a variable is atomic unless the variable is of type long or double [JLS, 17.4.7].
Tanmay said...
We can change the state of Immutable object, can't we? We can not instantiate again the object. But we can change the state, and I am not talking about String in particular. Any final class.
Anonymous said...
Would you say this article could help prepare one for an interview for a junior Java developer position? Or is it intermediate/advanced level?
Anonymous said...
In my opinion , this article help prepare for around intermediate positions, as there are aspects which can't be understand by simple demo code's.
javin paul said...
@Anonymous, you are right, writing thread-safe, concurrent and performance code requires lot of experience and programming skill. This article is meant to teach you basics e.g. how you achieve thread-safety by just making an object immutable in Java.
Anonymous said...
Can you please explain how the first example in this article is not thread safe.
It would have thread safety issues if the counter variable is static.
Unknown said...
NIce comments...
Blog do armando said...
nice my friend!
good explanation!
yiping said...
Thanks to the author and all the commentors
learn a lot
Post a Comment
Recommend
-
125
7 Techniques for thread-safe classes Almost every Java application uses threads. A web server like Tomcat process each request in a separate worker thread, fat clients process long-running requests in dedicated worker threads, and even ba...
-
82
ump A universal thread-safe memory pool. This simple memory pool can be used if following conditions are satisfied: (1) The memory sizes are some fixed numbers. E.g, 32 ,
-
9
Fix high CPU issue for ASP.NET - Dictionary was not thread-safe We have a ASP.NET application and suffered from high CPU issue occasionally - for years. It’s in production code and hard to reproduce. Fortunately, we got two dum...
-
5
A proper thread safe memory cache The Core 2.2 IMemoryCache is in theory thread safe. But if you call GetOrCreateAsync from multiple threads the factory Func will be called multiple times. Whi...
-
4
3 ways to make your ruby object thread-safe Let’s say you have an object and you know or suspect it might be used (called) from many threads. What can you do to make it safe to use in such a way? 1. Make it...
-
4
-
1
Download source 3 most common ways to check for null-value and raise an Even In articles on Internet, you will find a lot of discussions on...
-
6
Thread and Non-Thread Safe Go SetJanuary 26, 2018 · 2 min · Benjamin BengfortI came across this now archived project that implements a set data structure in Go and was intrigued b...
-
1
Making Golang Packages Thread-safePhoto by
-
2
Safely writing code that isn't thread-safe An under-appreciated Rust feature 2022-11-22 One of the nice things about the Rust prog...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK