How to make a class thread-safe in Java?



A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads.

The HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.

Example:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;

public class HashMapSyncExample {
   public static void main(String args[]) {

      HashMap hmap = new HashMap();
      hmap.put(2, "Raja");
      hmap.put(44, "Archana");
      hmap.put(1, "Krishna");
      hmap.put(4, "Vineet");
      hmap.put(88, "XYZ");

      Map map= Collections.synchronizedMap(hmap);
      Set set = map.entrySet();
      synchronized(map){
            Iterator i = set.iterator();
          // Display elements
         while(i.hasNext()) {
               Map.Entry me = (Map.Entry)i.next();
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
         }
      }
   }
}

In the above example, we have a HashMap it is having integer keys and String type values. In order to synchronize it we are using Collections.synchronizedMap(hashmap). It returns a thread-safe map backed up by the specified HashMap.

Output:

1: Krishna
2: Raja
4: Vineet
88: XYZ
44: Archana
raja
Published on 29-May-2019 14:56:10
Advertisements