Java - Difference Between Synchronized and Concurrent Collections

Synchronized Collection vs Concurrent Collection in Java: Here, we are going to learn what are the Java - Difference Between Synchronized and Concurrent Collections programming language? By Preeti Jain Last updated : March 30, 2024

Synchronized Collection

  • Now, we will see what is synchronize? Here, synchronize means only one thread is allowed to operate on an object at a time or in other words the object(which is synchronized) can't be modified by multiple threads simultaneously.
  • Synchronized Collection can be modified by one thread at a time(i.e. it is not possible to modify or access Synchronized Collection by multiple threads simultaneously).
  • Synchronized Collection has low performance than Concurrent Collection because at a time only one thread is allowed to operate on an object so it increases the waiting time of the threads.
  • Synchronized Collection acquires the lock on the entire Collection object which provides thread-safety.
  • SynchronizedMap is a static inner class of Collections class which is available in java.util.Collections.
  • In SynchronizedMap it acquires the lock on entire Map object and it wraps all the methods of Map interface with synchronized keyword.
  • SynchronizedMap may allow null keys and null values depend on the real Collections class.

Example of Synchronized Collection

import java.util.*;

class SynchronizedCollectionClass {
    public static void main(String[] args) {
        try {
            Set set = new HashSet();
            
            set.add(10);
            set.add(20);
            set.add(30);
            set.add(40);
            set.add(50);
            
            System.out.println("Current Set is :" + set);
            Collection collection = Collections.synchronizedCollection(set);
            System.out.println("Synchronized Collection is :" + set);
        } catch (IndexOutOfBoundsException ex) {
            System.out.println("Exception :" + ex.getMessage());
        }
    }
}

Output

E:\Programs>javac SynchronizedCollectionClass.java

E:\Programs>java SynchronizedCollectionClass
Current Set is :[50, 20, 40, 10, 30]
Synchronized Collection is :[50, 20, 40, 10, 30]

Concurrent Collection

  • Now, we will see what is Concurrent? Here, concurrent means only multiple threads are allowed to operate on an object at a time or in other words the object (which is concurrent) can be modified by multiple threads simultaneously.
  • Concurrent Collection can be modified by multiple threads at a time(i.e. it is possible to modify or access Concurrent Collection by multiple threads simultaneously).
  • Concurrent Collection has high performance than Synchronized Collection because at a time multiple threads are allowed to operate on an object so it decreases the waiting time of the threads.
  • More than one threads can perform read-write operation concurrently still it provides Thread Safety.
  • ConcurrentHashMap is a class introduced in Java 5 that is available in java.util package.
  • ConcurrentHashMap divides Map object into different parts and every thread acquires the lock on every part.
  • As we know default concurrency level is 16 that means maximum 16 threads are allowed to access an object simultaneously by default and we can increase and decrease concurrency level if we want.
  • ConcurrentHashMap does not allow null keys and null values.

Example of Concurrent Collection

// We will see in a program why Concurrent concept is required

import java.util.*;

class ConcurrentClass extends Thread {
    static LinkedList ll = new LinkedList();
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            System.out.println("ConcurrentClass" +
                " will add element");
        }

        // By using add() method to add an element in Concurrent Class Thread
        ll.add("Java");
    }

    public static void main(String[] args)
    throws InterruptedException {
        ll.add("C");
        ll.add("C++");
        ll.add("Ruby");
        ll.add("Python");

        // Creating an instance of ConcurrentClass and it will modify 
        ConcurrentClass cc = new ConcurrentClass();
        cc.start();

        // Iterating LinkedList 
        Iterator iterator = ll.iterator();
        while (iterator.hasNext()) {
            String str = (String) iterator.next();
            System.out.println(str);
            Thread.sleep(8000);
        }
        System.out.println(ll);
    }
}

Output

E:\Programs>javac ConcurrentClass.java

E:\Programs>java ConcurrentClass
C
Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.LinkedList$ListItr.checkForComodification
        (LinkedList.java:953)
        at java.util.LinkedList$ListItr.next(LinkedList.java:886)
        at ConcurrentClass.main(ConcurrentClass.java:34)

Difference Between Synchronized and Concurrent Collections in Java

The following table shows the differences between Synchronized Collection and Concurrent Collection in Java:

Sr. No. Synchronized Collection Concurrent Collection
1. Synchronized collection locks entire collection during operations. Concurrent collection allows multiple threads to access collection simultaneously.
2. Synchronized collection is slower due to locking overhead. Concurrent collection is faster due to optimized concurrency control.
3. Synchronized collection may block threads waiting for the lock. Concurrent collection is typically non-blocking, threads do not wait for each other.
4. Synchronized collection requires external synchronization for safe iteration. Concurrent collection supports safe concurrent iteration without external synchronization.
5. Synchronized collection is easier to use, as synchronization is implicit. Concurrent collection requires more careful management of concurrent access.
6. Synchronized collection provides coarse-grained locking, locking the entire collection. Concurrent collection provides fine-grained concurrency control locks only specific elements.
7. Synchronized collection has higher potential for thread contention, leading to longer wait times. Concurrent collection has Lower contention, resulting in shorter wait times for threads.
8. Synchronized collection is limited scalability under heavy contention due to lock contention. Concurrent collection is better scalability under heavy contention due to reduced contention points.
9. Synchronized collection has higher memory overhead due to synchronization-related data structures. Concurrent collection has lower memory overhead, as synchronization mechanisms are more lightweight.
10. Synchronized collection is suitable for low to moderate concurrent access scenarios. Concurrent collection is ideal for highly concurrent environments with frequent data access by multiple threads.

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.