How to create synchronized collection from collection

How to create synchronized collection from collection

Answer: To synchronized collection put synchronization wrappers to add automatic synchronization i.e. thread-safety on an arbitrary collection.
Collections class has defined six methods to synchronized arbitrary collection and every six core collection interfaces — Collection, List, Set, SortedSet, Map and SortedMap will have one static factory method below:

public static <T> Collection<T> synchronizedCollection(Collection<T> c);
public static <T> Set<T> synchronizedSet(Set<T> s);
public static <T> List<T> synchronizedList(List<T> list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);

 

Please note: When you use synchronized method it returns synchronized i.e. thread-safe map that is backed by specified map and in order to guarantee serial access it is necessary that all access to backing map is accomplished through returned map.

It is required that user should manually synchronize on returned map while iterating over any of its collection views as shown in below class:

package com.javahonk;

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

public class SynchronizedCollection {

	public static void main(String[] args) {

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

	map.put("Java", "Java");
	map.put("Honk", "Honk");
	map.put("Test", "Test");
	Map<String, String> synchronizedMap = 
			Collections.synchronizedMap(map);

	// Needn't be in synchronized block
	Set<String> s = synchronizedMap.keySet();  

	synchronized (map) {

		// Must be in synchronized block
		Iterator<String> i = s.iterator(); 
	      while (i.hasNext())
	          System.out.println(i.next());

		}

	}

}

 

Output:

synchronized_collection

Leave a Reply

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