by BehindJava

How to make your collections thread-safe?

Home » java » How to make your collections thread-safe?

In this tutorial we are going to learn about making the collections as thread-safe.

  • Thread safe collections can be deceiving.
  • The problem is there are several levels of thread safe collections. I find that when most people say thread safe collection what they really mean “a collection that will not be corrupted when modified and accessed from multiple threads”.
  • Collections class of java.util package methods that exclusively work on collections these methods provide various additional operations which involves the code that changes itself every time it runs, but the function of the code (its semantics) will not change at all.
  • There are different variants of the synchronizedCollection() method as shown below.
  • static Collection synchronizedCollection(Collection c) This method accepts any collection object and, returns a synchronized (thread-safe) collection backed by the specified collection.
  • static List synchronizedList(List list) This method accepts an object of the List interfacereturns a synchronized (thread-safe) list backed by the specified list.
  • static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) This method accepts an object of the Map interface and, returns a synchronized (thread-safe) map backed by the specified map.
  • static Set synchronizedSet(Set s) This method accepts an object of Set interface and, returns a synchronized (thread-safe) set backed by the specified set.
  • static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) This method accepts an object of the Map interface and, returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
  • static SortedSet synchronizedSortedSet(SortedSet s) This method accepts an object of the synchronizedSortedSet interface and, returns a synchronized (thread-safe) sorted set backed by the specified sorted set.

Example:

import java.util.Collection;
import java.util.Collections;
import java.util.Vector;
public class CollectionReadOnly {
   public static void main(String[] args) {
      //Instantiating an ArrayList object
      Vector<String> vector = new Vector<String>();
      vector.add("JavaFx");
      vector.add("Java");
      vector.add("WebGL");
      vector.add("OpenCV");
      System.out.println(vector);
      Collection<String> synchronizedVector = Collections.synchronizedCollection(vector);
      System.out.println("Synchronized "+synchronizedVector);
      synchronizedVector.add("CoffeeScript");
   }
}

Output:

[JavaFx, Java, WebGL, OpenCV]
Synchronized [JavaFx, Java, WebGL, OpenCV]