3

How to write Thread-Safe Code in Java

 9 months ago
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

thread-safety or thread-safe code in Java refers to code which can safely be used or shared in concurrent or multi-threading environment and they will behave as expected. any code, class, or object which can behave differently from its contract on the concurrent environment is not thread-safe. thread-safety is one of the risks introduced by using threads in Java and I have seen java programmers and developers struggling to write thread-safe code or just understanding what is thread-safe code and what is not?
16596063615762eb9559b523f.png
Video Player is loading.
Loaded: 0.00%
This will not be a very detailed article on thread-safety or low-level details of synchronization in Java instead we will keep it simple and focus on one example of non-thread-safe code and try to understand what is thread-safety and how to make a code thread-safe.
Btw, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at the Java Multithreading, Concurrency, and Performance Optimization course by Michael Pogrebinsy on Udemy. 

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

Here is an example of a non-thread-safe code, look at the code, and find out why this code is not thread-safe?
 * Non Thread-Safe Class in Java
public class Counter {
    private int count;
     * This method is not thread-safe because ++ is not an atomic operation
    public int getCount(){
        return count++;
The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.

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.
You can further check Multithreading and Parallel Computing in Java to learn more about essential multithreading concepts like atomicity and compound operation. It's a good course to learn multithreading in JAva. 

How to make code Thread-Safe in Java

There are multiple ways to make this code thread-safe in Java:
1) Use the synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes the possibility of coinciding or interleaving.
2) use Atomic Integer, which makes this ++ operation atomic and since atomic operations are thread-safe and saves the cost of external synchronization.
Here is a thread-safe version of Counter class in Java:
 * Thread-Safe Example in Java
public class Counter {
    private int count;
    AtomicInteger atomicCount = new AtomicInteger( 0 );
     * This method thread-safe now because of locking and synchornization
    public synchronized int getCount(){
        return count++;
     * This method is thread-safe because count is incremented atomically
    public int getCountAtomically(){
        return atomicCount.incrementAndGet();
And, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at the Java Multithreading, Concurrency, and Performance Optimization course by Michael Pogrebinsy on Udemy. 

This is an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance.
thread safety in Java multithreading

Important points about Thread-Safety in Java

Here are some points worth remembering to write thread-safe code in Java, this knowledge also helps you to avoid some serious concurrency issues in Java-like race condition or deadlock in Java:
1) Immutable objects are by default thread-safe because their state can not be modified once created. Since String is immutable in Java, it's inherently thread-safe.
2) Read-only or final variables in Java are also thread-safe in Java.
3) Locking is one way of achieving thread-safety in Java.
4) Static variables if not synchronized properly become a major cause of thread-safety issues.
5) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String, etc.
6) Atomic operations in Java are thread-safe like reading a 32-bit int from memory because it's an atomic operation it can't interleave with other threads.
7) local variables are also thread-safe because each thread has there own copy and using local variables is a good way to write thread-safe code in Java.
8) In order to avoid thread-safety issues minimize the sharing of objects between multiple threads.
9) Volatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct JVM not to reorder or optimize code from threading perspective.
That’s all on how to write thread-safe class or code in Java and avoid serious concurrency issues in Java. To be frank, thread-safety is a little tricky concept to grasp, you need to think concurrently in order to catch whether a code is thread-safe or not. 

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.
Further Learning
Multithreading and Parallel Computing in Java
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice Course by Heinz Kabutz
Other multi-threading articles you may like
  • 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)
Thanks for reading this article. If you like this article about Thread vs Executor in Java then please share it with your friends and colleagues. If you have any suggestions or feedback then please drop a comment. 
P. S. - And, if you are looking for a free course to learn Multithreading concepts in Java then you can also check out this free Java Multithreading course on Udemy. It is a fantastic free online course to learn  Java Multithreading from scratch as well.

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.

January 11, 2012 at 12:29 AM

vasanth said...

Super

April 30, 2012 at 7:07 AM

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.

December 9, 2012 at 3:07 PM

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. :(

April 17, 2013 at 4:58 AM

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();
}
}

May 9, 2013 at 9:21 AM

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].

May 27, 2013 at 6:28 AM

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.

April 9, 2014 at 12:46 PM

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?

June 15, 2014 at 10:18 PM

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.

February 3, 2016 at 8:48 AM

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.

February 6, 2016 at 1:20 AM

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.

March 11, 2016 at 4:07 AM

Unknown said...

NIce comments...

April 28, 2016 at 3:02 AM

Blog do armando said...

nice my friend!
good explanation!

March 4, 2017 at 6:25 AM

yiping said...

Thanks to the author and all the commentors
learn a lot

November 15, 2021 at 6:56 AM

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
    • www.tuicool.com 5 years ago
    • Cache

    A universal thread-safe memory pool

    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
    • andersmalmgren.com 3 years ago
    • Cache

    A proper thread safe memory cache

    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
    • blog.arkency.com 3 years ago
    • Cache

    3 ways to make your ruby object thread-safe

    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
    • www.codeproject.com 2 years ago
    • Cache

    Thread-safe Events in C#

    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
    • bbengfort.github.io 2 years ago
    • Cache

    Thread and Non-Thread Safe Go Set

    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
    • madflojo.medium.com 1 year ago
    • Cache

    Making Golang Packages Thread-safe

    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