How to make a collection thread safe in java?

JavaObject Oriented ProgrammingProgramming

The Collections class of java.util package methods that exclusively work on collections these methods provide various additional operations which involves polymorphic algorithms.

This class provides different variants of the synchronizedCollection() method as shown below −

Sr.NoMethods & Description
1static <T> Collection<T> synchronizedCollection(Collection<T> c)
This method accepts any collection object and, returns a synchronized (thread-safe) collection backed by the specified collection.
2static <T> List<T> synchronizedList(List<T> list)
This method accepts an object of the List interfacereturns a synchronized (thread-safe) list backed by the specified list.
3static <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.
4static <T> Set<T> synchronizedSet(Set<T> s)
This method accepts an object of Set interface and, returns a synchronized (thread-safe) set backed by the specified set.
5static <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.
6static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> 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

 Live Demo

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]
raja
Published on 15-Oct-2019 07:07:08
Advertisements