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

Comparator Example

Below is an example of Comparator

import java.util.Comparator;
import java.util.TreeSet;

public class MySetWithCompr {

    public static void main(String a[]){
    	MyComp obj = new MyComp();
        TreeSet<String> ts = new TreeSet<String>(obj);
        ts.add("RED");
        ts.add("ORANGE");
        ts.add("BLUE");
        ts.add("GREEN");
        ts.add("H");
        ts.add("AB");
        //Comparator cmp = ts.comparator();

        System.out.println(ts);
    }
}

//Comparator can be used for any type
//usage with String is given below
class MyComp implements Comparator<String>{

    public int compare(String str1, String str2) {
        //return str1.compareTo(str2);
    	//return str2.compareTo(str1);//sort in reverse order
    	//System.out.println("Hello from Comparator");
    	return (str1.length()-str2.length());
    }

}


You may also like to read:
Comparable Example
Difference between Comparator and Comparable

Similarity and Difference between Comparator and Comparable interfaces

Below are Similarity and Difference between Comparator and Comparable interfaces

Similarity:
#1.Both are interfaces
#2.Both are used for specifying sorting order of the objects stored in a Collection

Difference:
#1.Packages they are available
Comparator interface is defined in java.util package, but Comparable interface is defined in java.lang package

#2.Methods they declare
Comparator interface declares method
public int compare (Object obj1, Object obj2) which returns a -ve, zero, or +ve integer as the first argument is less than, equal to, or greater than second respectively.

But Comparable interface declares method public int compareTo(Object obj)

#3.How to implement?
The class(whose objects need to be sorted) need to implement Comparable, and provide body for compareTo(Object obj) method.

Not the actual class(whose objects need to be sorted), but another class need to implement Comparator. Need to be sent as parameter while creating Collection, or to Collections.sort() method.

#4.Using Comparable, objects can be sorted only on one criteria. Using Comparator, objects can be sorted based on different criteria.

You may also like to read:
Comparable Example
Comparator Example

How to store objects in a HashSet Generic class

Below program shows how objects can be stored in any Collection. This program uses HashSet<T> instead of HashSet.

import java.util.HashSet;
import java.util.Iterator;

//Any objects can be stored in Set, or any other Collection
class Abc1
{
private int i,j;
Abc1(int i,int j)
{
this.i = i;
this.j = j;
}

public void display()
{
System.out.println(“Values are:”+i+” “+j);
}
}

public class SetObjectGeneric {
public static void main(String[] args) {

//Generic version of HasSet
HashSet<Abc1> hs = new HashSet<Abc1>();

//HashSet is internally implemented using hash table
Abc1 oa,ob,oc,od,oe;

oa = new Abc1(12,89);
ob = new Abc1(21,98);
oc = new Abc1(33,58);
od = new Abc1(68,89);
oe = new Abc1(32,26);

hs.add(oa);
hs.add(ob);
hs.add(oc);
hs.add(od);
hs.add(oe);

//System.out.println(” :”+hs);

Iterator itr = hs.iterator();
while(itr.hasNext())
{
Abc tmp = (Abc)itr.next();
tmp.display();
}

}

}

Also read our post How to store objects in a HashSet

How to store objects in a HashSet

Below program shows how objects can be stored in a Collection. Here all Objects stored in HashSet are of same type…in this example we are storing objects of class Abc, similarly any objects can be stored in a Collection.

import java.util.HashSet;
import java.util.Iterator;

//Any objects can be stored in Set, or any other Collection
class Abc
{
private int i,j;
Abc(int i,int j)
{
this.i = i;
this.j = j;
}

public void display()
{
System.out.println(“Values are:”+i+” “+j);
}
}

public class SetObjectDemo {
public static void main(String[] args) {

HashSet hs = new HashSet();

//HashSet is internally implemented using hash table
Abc oa,ob,oc,od,oe;

oa = new Abc(12,89);
ob = new Abc(21,98);
oc = new Abc(33,58);
od = new Abc(68,89);
oe = new Abc(32,26);

hs.add(oa);
hs.add(ob);
hs.add(oc);
hs.add(od);
hs.add(oe);

System.out.println(” :”+hs);

Iterator itr = hs.iterator();
while(itr.hasNext())
{
Abc tmp = (Abc)itr.next();
tmp.display();
}

}

}

You may also like How to store objects in a hashset generic class