Thread Safety in Java

Thread safety in java is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe.
  • Synchronization is the easiest and most widely used tool for thread safety in java.
  • Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
  • Use of locks from java.util.concurrent.locks package.
  • Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.
  • Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.
Java synchronized
Synchronization is the tool using which we can achieve thread safety, JVM guarantees that synchronized code will be executed by only one thread at a time. java keyword synchronized is used to create synchronized code and internally it uses locks on Object or Class to make sure only one thread is executing the synchronized code.
  • Java synchronization works on locking and unlocking of resource, before any thread enters into synchronized code, it has to acquire lock on the Object and when code execution ends, it unlocks the resource that can be locked by other threads. In the mean time other threads are in wait state to lock the synchronized resource.
  • We can use synchronized keyword in two ways, one is to make a complete method synchronized and other way is to create synchronized block.
  • When a method is synchronized, it locks the Object, if method is static it locks the Class, so it's always best practice to use synchronized block to lock the only sections of method that needs synchronization.
  • While creating synchronized block, we need to provide the resource on which lock will be acquired, it can be XYZ.class or any Object field of the class.
  • synchronized(this) will lock the Object before entering into the synchronized block.
  • You should use the lowest level of locking, for example if there are multiple synchronized block in a class and one of them is locking the Object, then other synchronized blocks will also be not available for execution by other threads. When we lock an Object, it acquires lock on all the fields of the Object.
  • Java Synchronization provides data integrity on the cost of performance, so it should be used only when it's absolutely necessary.
  • Java Synchronization works only in the same JVM, so if you need to lock some resource in multiple JVM environment, it will not work and you might have to look after some global locking mechanism.
  • Java Synchronization could result in deadlocks, check this post about deadlock in java and how to avoid them.
  • Java synchronized keyword cannot be used for constructors and variables.
  • It is preferable to create a dummy private Object to use for synchronized block, so that it's reference can't be changed by any other code. For example if you have a setter method for Object on which you are synchronizing, it's reference can be changed by some other code leads to parallel execution of the synchronized block.
  • We should not use any object that is maintained in a constant pool, for example String should not be used for synchronization because if any other code is also locking on same String, it will try to acquire lock on the same reference object from String pool and even though both the codes are unrelated, they will lock each other.
Here is the code changes we need to do in above program to make it thread safe.
//dummy object variable for synchronization
    private Object mutex=new Object();
    //using synchronized block to read, increment and update count value synchronously
    synchronized (mutex) {
Let's see some synchronization examples and what can we learn from them.
public class MyObject {
  // Locks on the object's monitor
  public synchronized void doSomething() { 
    // ...
// Hackers code
MyObject myObject = new MyObject();
synchronized (myObject) {
  while (true) {
    // Indefinitely delay myObject
Notice that hacker's code is trying to lock the myObject instance and once it gets the lock, it's never releasing it causing doSomething() method to block on waiting for the lock, this will cause system to go on deadlock and cause Denial of Service (DoS).
public class MyObject {
  public Object lock = new Object();
  public void doSomething() {
    synchronized (lock) {
      // ...

//untrusted code

MyObject myObject = new MyObject();
//change the lock Object reference
myObject.lock = new Object();
Notice that lock Object is public and by changing it's reference, we can execute synchronized block parallel in multiple threads. Similar case is true if you have private Object but have setter method to change it's reference.
public class MyObject {
  //locks on the class object's monitor
  public static synchronized void doSomething() { 
    // ...
// hackers code
synchronized (MyObject.class) {
  while (true) {
    Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay MyObject
Notice that hacker code is getting lock on class monitor and not releasing it, it will cause deadlock and DoS in the system.

Here is another example where multiple threads are working on same array of Strings and once processed, appending thread name to the array value.
package com.journaldev.threads;

import java.util.Arrays;

public class SyncronizedMethod {

    public static void main(String[] args) throws InterruptedException {
        String[] arr = {"1","2","3","4","5","6"};
        HashMapProcessor hmp = new HashMapProcessor(arr);
        Thread t1=new Thread(hmp, "t1");
        Thread t2=new Thread(hmp, "t2");
        Thread t3=new Thread(hmp, "t3");
        long start = System.currentTimeMillis();
        //start all the threads
        //wait for threads to finish
        System.out.println("Time taken= "+(System.currentTimeMillis()-start));
        //check the shared variable value now


class HashMapProcessor implements Runnable{
    private String[] strArr = null;
    public HashMapProcessor(String[] m){
    public String[] getMap() {
        return strArr;

    public void run() {

    private void processArr(String name) {
        for(int i=0; i < strArr.length; i++){
            //process data and append thread name
            addThreadName(i, name);
    private void addThreadName(int i, String name) {
        strArr[i] = strArr[i] +":"+name;

    private void processSomething(int index) {
        // processing some job
        try {
        } catch (InterruptedException e) {
Here is the output when I run above program.
Time taken= 15005
[1:t2:t3, 2:t1, 3:t3, 4:t1:t3, 5:t2:t1, 6:t3]
The String array values are corrupted because shared data and no synchronization. Here is how we can change addThreadName() method to make our program thread safe.
    private Object lock = new Object();
    private void addThreadName(int i, String name) {
        strArr[i] = strArr[i] +":"+name;
After this change, our program works fine and here is the correct output of the program.
Time taken= 15004
[1:t1:t2:t3, 2:t2:t1:t3, 3:t2:t3:t1, 4:t3:t2:t1, 5:t2:t1:t3, 6:t2:t1:t3]
That's all for thread safety in java, I hope you learned about thread safe programming and using synchronized keyword.

Popular posts from this blog

Async Task in Android

Shake effect in Android

Example For ListView Using BaseAdapter