Thread Safe Code and Thread Safety in Java

Posted By : Sanjay Saini | 29-Sep-2018

Hi Guys,

In this blog, I'm showing you how to write thread safe code in java.

Thread-safety or Thread-safe code in Java refers to code which can securely be done or participated in mutual or multi-threading situation and they will perform as required. any code, class or object which can act differently from its promise 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 many java programmer and developer trying to write thread-safe code or just understanding what is thread-safe code and what is not? This will not be the detailed blog on thread-safety or low-level details of synchronization in Java instead we will make it simple and focus on one example of non-thread-safe code and try to understand thread safety.

 

Way to make Thread-Safe Code in Java Example of Non Thread Safe Code in Java.

 

Here is an example of non thread-safe code

 

/*
 * Non Thread-Safe Code in Java
 */
public class Count {
  
    private int counter;
  
    /*
     * This action is not thread-safe because ++ increment is not an nuclear operation
     */
    public int getCounter(){
        return counter++;
    }
}

Above example is not thread-safe because ++ (increment operator) is not a nuclear operation and can be divided down into read, update and write operation. if many thread call getCounter() almost same time each of this three action may match or overlap with each other for example while thread 1 is updating value, thread 2 reads and but gets old value, which eventually let thread 2 override thread 1 increment and one count is lost because many threads called it concurrently.

 

How to create Thread-Safe code in Java?

 

There are many ways to make this code thread-safe in Java:

 

1) Use the synchronized keyword in Java and lock the getCounter() method so that only one thread can perform it at a time which removes the chance of coinciding or interleaving. 
2) use Atomic Integer, which makes this ++ operation atomic and since atomic methods are thread-safe and save the cost of outside synchronization.

here is a thread-safe version of ThreadSafeCount class in Java:

/*
 * Thread-Safe Code Example in Java
 */
public class ThreadSafeCount {
  
    private int counter;
    AtomicInteger atomicCount = new AtomicInteger( 0 );

  
   
    public synchronized int getCounter(){
        return counter++;
    }
  
    /*
     * This action is thread-safe because counter is incremented atomically
     */
    public int getCountAtomically(){
        return atomicCount.incrementAndGet();
    }
}

Important points about Thread-Safety in Java

 

Points needs to remember about Thread-Safety

Here is some points deserving remembering to write thread-safe code in Java, this information also helps you to bypass some serious concurrency problems in Java like race condition or deadlock in Java:

1) Immutable objects are by default thread-safe because there situation cannot be changed once created. Since String is immutable in Java, its genetically thread-safe.

2) Variables that are declared Final are also thread-safe in Java.

3) Locking is one process of completing thread-safety in Java.

4) Static variables if not synchronized correctly fits the major cause of thread-safety issues.

5) Many classes are thread safe in Java For Example : Vector, Hashtable, ConcurrentHashMap, String etc.

6) Nuclear operations in Java are thread-safe e.g. viewing a 32-bit int from memory because its a nuclear operation it can't interleave with other thread.

7) local variables are also thread-safe because every thread has there personal copy and using local variables is great way to writing thread-safe code in Java.

8) In order to avoid thread-safety issue reduce sharing of objects between multiple thread.

9) Volatile keyword in Java can further be used to guide thread not to cache variables and gathered from main memory and can also command JVM not to reorder or optimize code from threading perspective.

Thanks 

Sanjay Saini

About Author

Author Image
Sanjay Saini

Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.

Request for Proposal

Name is required

Comment is required

Sending message..