Difference between Concurrent, Synchronized and non Synchronized Collections

Difference between Synchronized, Concurrent and Non synchronized Java Collection
As known, java.util.Collection is base interface for java.util.Map, java.util.Set and java.util.List
And all implementations of these interfaces ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap are non synchronized , when used as is.

When a Collection is said to be thread safe?

A Collection is said thread safe, when multiple threads can access, update data in single instance of collection, with out causing corruption/loss of data in that Collection.

How to get synchronized version of List, Set or Map?

Collections utility class provides Concurrent version of each Collection by invoking below methods

Set st = Collections.getSynchronizedSet();
List lst = Collections.getSynchormizedList();
Map mp = Collections.getSynchronizedMap();

Non synchronized collections are not thread safe. Where as, both Synchronized and Concurrent Collections are thread safe.

In addition to above, legacy collections like, Hastable, Vector, Properties are also synchronized.

Though above Collections are thread safe, they are not well suitable for Applications which need to be highly Scalable, and to perform time bound operations. The reason is, synchronization is achieved by making all the public methods of the collection “Synchronized”.

As a solution to this Concurrent Collections have been added during Java. The Concurrent Collection implementations provide much higher concurrency while preserving thread safety.

java.util.concurrent package includes a number of additions to the Java Collections Framework.
ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations.
Implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches.
An implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.

Let us see, why synchronized collections cause performance hit, compared to their Concurrent counter parts.
Taking Hashtable and ConcurrentHashMap, as an example. Both of them are thread safe, but consider using them on large number of elements. Hashtable performance would get degraded as the number of elements increase.

But performance of ConcurrentHashMap will not get degraded as the size grows. The reason for this is, underlying implementation of ConcurrentHashMap uses segmentation, i..e it divides entire Collection into multiple segments, and each segment will be locked or unlocked on need basis, so that other threads can simultaneously access other segments which are not locked.

You may also like to read:
Difference between class level, block level and method level synchronization
HashSet Generic class
How to store user defined objects in a collection

Properties class

The Properties class extends the Hashtable class and implements the Map interface.It represents the persistent set of properties.
Each key and its  value associated with it in the property list is a string.This class has the following constructors:-

public Properties()
public Properties(Properties def)
The first constructor constructs an empty property list with no default values.

The  second constructor will create a empty property with a default def. The property list def is searched if the property key is not found in the original property list.

Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String comment) writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating xml document.
public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating xml document with specified encoding.


Below example shows how to use Properties class to set key and value pairs, and get the value.

   import    java.io.*;
   import    java.util.*;
   public      class    Test {
   public      static      void    main(String[] args)  throws    Exception{
 Properties p=  new    Properties();
 p.setProperty(“name”,”ravi”);
 p.setProperty(“email”,”ravi@gmail.com”);
 p.getProperty(“name”);
 }
 }


Below example shows how to use Properties class to get configuration values, from a properties file.

   import    java.util.*;
   import    java.io.*;
   public      class    LoadDemo {
   public      static      void    main(String[] args)  throws    Exception{
     FileReader reader=  new    FileReader(“newFile.properties”);

     Properties p=  new    Properties();
     p.load(reader);

     System.out.println(p.getProperty(“username”));
     System.out.println(p.getProperty(“password”));
 }
 }


Below example shows how to use Properties class to set key and value pairs, to a properties file.

 import java.io.*;
 import java.util.*;
 public class PropertiesExample {
           public static void main(String args[]) {
      try {
   Properties std_code = new Properties();

     grades.setProperty(“Bangalore”, “080”);
    grades.setProperty(“Delhi”, “011”);
     grades.setProperty(“Mumbai”, “022”);
    grades.setProperty(“Chennai”, “044”);
    grades.setProperty(“Kolkata”, “033”);

   // Save the grades properties using store() and an output stream
  FileOutputStream out = new FileOutputStream “stdcodes.properties”);
     std_code.store(out, null);
     out.close();

  // load the properties file using load() and an input stream
   FileInputStream in = new FileInputStream(“stdcodes.propertie  std_code.load(in);
   in.close();

    // iterate properties file to get key-value pairs
     for (String key : std_code.stringPropertyNames()) {
     String value = std_code.getProperty(key);
      System.out.println(“The STD code of  ” + key + ” is: ” + value);
                              }

       } catch (IOException eio) {
     System.out.println(eio.getMessage());
      eio.printStackTrace();
                    }
           }
 }


Below example shows how to retrieve and store Configuration properties in a XML file.
NOTE: Below is sample XML file format

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is to test</comment>
<entry key="pname1">pval1</entry>
<entry key="pname2">pval</entry>
<entry key="pname3">pval3</entry>
<entry key="pname4">pval4</entry>
</properties>
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.*;

 public class PropertiesloadfromXMLDemo {

    public static void main(String[] args) {
    Properties pro = new Properties();

    // add some properties
    pro.put("pname1", "pval1");
    pro.put("pname2", "pval2");

    try {

    // create a output and input as a xml file
    FileOutputStream fos = new FileOutputStream("abcproperties.xml");
    FileInputStream fis = new FileInputStream("abcproperties.xml");

    // store the properties in the specific xml
    pro.storeToXML(fos, null);

    // load key/values from the xml
    pro.loadFromXML(fis);

    // Now print all the key/values to Standard output
    pro.list(System.out);

    } catch (IOException ex) {
    ex.printStackTrace();
    }

    }
 }