Skip to Content

Get Synchronized Map from Java HashMap example

  1. /*
  2.   Get Synchronized Map from Java HashMap example
  3.   This java example shows how to get a synchronized Map from Java HashMap using
  4.   synchronizedMap method of Collections class.
  5. */
  6.  
  7. import java.util.HashMap;
  8. import java.util.Collections;
  9. import java.util.Map;
  10.  
  11. public class GetSynchronizedMapFromHashMapExample {
  12.  
  13.   public static void main(String[] args) {
  14.     //create HashMap object
  15.     HashMap hashMap = new HashMap();
  16.    
  17.     /*
  18.       Java HashMap is NOT synchronized. To get synchronized Map from
  19.       HashMap use
  20.       static void synchronizedMap(Map map) method of Collections class.
  21.     */
  22.    
  23.     Map map = Collections.synchronizedMap(hashMap);
  24.    
  25.     /*
  26.        Use this map object to prevent any unsynchronized access to original
  27.        HashMap object.
  28.     */
  29.    
  30.   }
  31. }