Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Concurrent collections in Java, details, advantages, examples

  • Balkand Ramayana story in Hindi | रामायण बाल कांड राम का जन्म
    Balkand Ramayana story in Hindi | रामायण बाल कांड राम का जन्म Spiritual
  • Ramayana Uttar Kand Luv Kush| रामायण उत्तर कांड इन हिंदी
    Ramayana Uttar Kand Luv Kush | रामायण उत्तर कांड इन हिंदी Spiritual
  • जन्माष्टमी व्रत पूजा विस्तार से | दही हांडी | Krishna Janmashtami Puja
    जन्माष्टमी व्रत पूजा विस्तार से, दही हांडी: Krishna Janmashtami Puja Festival
  • Kishore Kumar Biography in Hindi | किशोर कुमार की जीवनी
    Kishore Kumar Biography in Hindi | किशोर कुमार की जीवनी Biography
  • America Independence Day : 4th July USA | USA Birthday
    America Independence Day : 4th July USA | USA Birthday General Knowledge
  • Vedaant Madhavan Biography in Hindi, Family, School, Age
    Vedaant Madhavan Biography in Hindi, Family, School, Age Biography
  • Pythagorean Theorem in Hindi, Definition
    Pythagorean Theorem in Hindi, Definition, Formula, Proof पाइथागोरस थ्योरम क्या है जानिए हिंदी में? Science
  • Holi kyon manate hain in hindi? | Festival of colors in hindi
    Holi kyon manate hain in hindi? | Festival of colors in hindi Festival

Concurrent collections in Java, details, advantages, examples

Posted on December 18, 2021October 27, 2022 By GeekCer Education No Comments on Concurrent collections in Java, details, advantages, examples
Concurrent collections in Java, details, advantages, examples

Concurrent collections in Java are designed with the goal of allowing many threads to access the same data in a synchronized manner. In other words, Concurrent collections in Java allow many threads to access the same data synchronously.

If you’re familiar with Java Collections, you’re probably aware that most Collection classes aren’t thread-safe by default. Take, for example, Java’s ArrayList, LinkedList, HashMap  classes. We must manually make the collection thread-safe if we want it to be thread-safe.

If we iterate the collection class, if multiple threads are working on it, and if another thread tries to modify the collection, we get ConcurrentModificationException. This is due to the fact that the class is not thread-safe. For programmers developing multithreaded applications, this was a major concern.

However, the java.util.concurrent package has a set of thread-safe collection classes. These thread-safe classes help developers avoid the issues mentioned above.

Table of Contents

  • Advantages of using concurrent classes
  • Top Concurrent Collections in Java
    • ConcurrentHashMap in Java with example
    • CopyOnWriteArrayList in java with example
    • CopyOnWriteArraySet in Java with example

Advantages of using concurrent classes

  • Concurrent classes provide unique locking system.
  • All concurrent classes are guaranteed to be thread safe.
  • The performance of concurrent classes are much better than that of traditional thread-safe classes.
  • We can update the data while iterating the collection elements, so we will not get ConcurrentModificationException.

Top Concurrent Collections in Java

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet

ConcurrentHashMap in Java with example

The most popular class is ConcurrentHashMap, which is thread-safe and uses segment locking rather than whole-object locking. It can manage a lot of concurrency and can be used instead of Hashtable and SynchronizedMap.

ConcurrentHashMap has a higher scalability than the synchronised version. There is no need to lock during iteration, which improves scalability and speed.

Internally, the entire ConcurrentHashMap object will be partitioned into many pieces, each with its own lock. It is based on the locking of bucket levels.

In ConcurrentHashMap, null entries are not permitted for both the key and the value.

ConcurrentHashMap example

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapDemo {

	public static void main(String[] args) {
		ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>();
		cmap.put("Key 1", "Value 1");
		cmap.put("Key 2", "Value 2");
		cmap.put("Key 3", "Value 3");
		for (Map.Entry<String, String> map : cmap.entrySet()) {
			System.out.println(map.getKey() + "  " + map.getValue());
		}

	}
}
Output:
Key 1  Value 1
Key 2  Value 2
Key 3  Value 3

CopyOnWriteArrayList in java with example

CopyOnWriteArrayList is a thread-safe alternative to synchronized ArrayList.  It creates a clone copy of the list when we perform update operation.

Because each update action will result in a cloned copy of the list, it is never suggested to use it because it is inefficient in terms of performance.

CopyOnWriteArrayList allows the duplicate  and heterogenous object. You can insert null values and the insertion order is preserved.

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListDemo {

	public static void main(String[] args) {
		CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
		list.add("Concurrent Collections");
		list.add("Traditional Collections");
		System.out.println(list);

	}
}
Output:
[Concurrent Collections, Traditional Collections]

CopyOnWriteArraySet in Java with example

CopyOnWriteArraySet is a thread-safe alternative to synchronized HashSet. It creates a clone copy of the set when we perform update operation.

Duplicate elements are not allowed in CopyOnWriteArraySet, however heterogeneous elements are allowed.

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

public class CopyOnWriteArraySetDemo {

	public static void main(String[] args) {
		CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>();
		set.add("First Element");
		set.add("Second Element");
		set.add("Third Element");
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}
}
Output:
First Element
Second Element
Third Element

In conclusion, Hope you got some idea about Concurrent Collections, When to use it?, Why should you use it?

Also Read: Java fork/join for parallel programming

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java Tags:Concurrent collections interview questions, What is the use of ConcurrentHashMap?

Post navigation

Previous Post: Lambda Expression in Java 8 | Functional Interface | Example
Next Post: Java 8 interview questions and answers, Java Stream, Optional

More Related Articles

What is Array in Java? Types of array in Java What is Array in Java? Types of array in Java Java
Immutable class in Java Immutable class in Java | How to create Immutable class in Java Important
Java 11 new Features (With example Programs) Java 11 new Features (With example Programs) Important
Difference between Interface and Abstract class Difference between Interface and Abstract class Differences
Top Java Programs for Coder Top Java Programs for Coder Java
Variables in Java Variables in Java Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java Home
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Keywords
  • Java Operators
  • Java If-else Statement
  • Java Switch
  • Java Loop
  • Java Arrays
  • Method Overloading in Java
  • Java OOP
  • Java Collections
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Multithreading in java
  • Thread Synchronization
  • Exception Handling
  • Java JDBC Driver
  • Java Database Connectivity steps
  • Lambda Expressions
  • Concurrent Collections
  • National Farmers Day in Hindi | राष्ट्रीय किसान दिवस पर निबंध | चौधरी चरण सिंह जयंती
  • Human rights day in Hindi: 10 दिसंबर ह्यूमन राइट्स डे
  • Unicef day is celebrated on December 11 | Speech on unicef day
  • Indian Navy Day: जल सेना दिवस कब और क्यों मनाया जाता है?
  • P V Sindhu Biography in Hindi, Badminton, State, Caste पी. वी. सिंधु जीवन परिचय, कहानी, राज्य, जाति
  • Draupadi Murmu Biography In Hindi | द्रौपदी मुर्मू की जीवनी
  • IPv4 Vs IPv6 | Difference between IPv4 and IPv6
    IPv4 Vs IPv6 | Difference between IPv4 and IPv6 Differences
  • Similarities and difference between OSI and TCP/IP model
    OSI vs TCP/IP Model, Similarities and difference between OSI and TCP/IP model Networking
  • Difference between Internet and Intranet
    Difference between Internet and Intranet Differences
  • TCP/IP Model, Full Form, Layers and their Functions
    TCP/IP Model, Full Form, Layers and their Functions Networking
  • Network kya hai (नेटवर्क क्या है)
    Network kya hai (नेटवर्क क्या है) Networking
  • OSI Model | 7 Layers of OSI Model in Computer network
    OSI Model | 7 Layers of OSI Model in Computer network, Functions Networking
  • Difference between TCP and UDP
    Difference between TCP and UDP | TCP vs UDP examples Differences
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved