Tuesday, November 24, 2020

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?


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.



how to write thread-safe code in java exampleThat’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.


13 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!

Post a Comment