Make List Set Map elements synchronized

Make List Set Map elements synchronized

In java framework public class Collections which exends Ojbect consists of static methods that work on and return collections. To make List Set or Map elements synchronized this class provides below three methods:

  • synchronizedList(List list): Returns synchronized which is thread safe list and backed by specified list.
  • synchronizedMap(Map<K,V> m): Returns synchronized which is thread safe map backed by specified map.
  • synchronizedSet(Set s): Returns synchronized which is thread safe set backed by specified set.

Below is example java class:

package com.javahonk.synchronizedTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SynchronizedTest {

    public static void main(String[] args) {

    // Synchronized List example
    List<String> list = new ArrayList<String>();

    list.add("Java");
    list.add("Honk");
    list.add("Test");

    // synchronized list
    List<String> synchronizedList = Collections
        .synchronizedList(list);

    System.out.println("Synchronized list:" 
    + synchronizedList);

    // Synchronized Set example
    Set<String> set = new HashSet<String>();

    set.add("Java");
    set.add("Honk");
    set.add("Test");

    // synchronized Set
    Set<String> synchronizedSet = Collections
        .synchronizedSet(set);

    System.out.println("Synchronized set: " 
    + synchronizedSet);

    // Synchronized Map example
    Map<String,String> map = new HashMap<String,String>();

    map.put("Java","Java");
    map.put("Honk","Honk");
    map.put("Test","Test");

    // synchronized Map
    Map<String,String> synchronizedMap = Collections
        .synchronizedMap(map);

    System.out.println("Synchronized Map: " 
    + synchronizedMap);
    }

}

Output:

Make List Set Map elements synchronized

 

Leave a Reply

Your email address will not be published. Required fields are marked *