Collection synchronized

In this chapter you will learn:

  1. Get a synchronized collection
  2. How to create a synchronized Map

Get a synchronized collection

A synchronized collection is good for multithread application. By using synchronized collections we can coordinate the usage of a collection among different applications.

We can make a collection to be synchronized using the following methods.

  • static<T> Collection<T> synchronizedCollection(Collection<T> c)
  • static<T> List<T> synchronizedList(List<T> list)
  • static<K,V> Map<K,V> synchronizedMap(Map<K,V> m)
  • static<T> Set<T> synchronizedSet(Set<T> s)
  • static<K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
  • static<T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*  java2 s  . c  o  m*/
public class Main {
  public static void main(String[] args) {
    Collection<String> c = Collections.synchronizedCollection(new ArrayList<String>());
    List<String> list = Collections.synchronizedList(new ArrayList<String>());
    Set<String> s = Collections.synchronizedSet(new HashSet<String>());
    Map<String,String> m = Collections.synchronizedMap(new HashMap<String,String>());
  }
}

Create a synchronized Map

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
//from jav a2 s  .c o m
public class MainClass {
  public static void main(String args[]) {
    Set simpsons = new HashSet();
    simpsons.add("B");
    simpsons.add("H");
    simpsons.add("L");
    simpsons = Collections.synchronizedSet(simpsons);
    synchronized (simpsons) {
      Iterator iter = simpsons.iterator();
      while (iter.hasNext()) {
        System.out.println(iter.next());
      }
    }
    Map map = Collections.synchronizedMap(new HashMap(89));
    Set set = map.entrySet();
    synchronized (map) {
      Iterator iter = set.iterator();
      while (iter.hasNext()) {
        System.out.println(iter.next());
      }
    }
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Create singleton set, map or list
  2. How to create singleton collection from array
Home » Java Tutorial » Collections
Iterator
ListIterator
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue