Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
ConcurrentModificationException in Java with Examples
Next article icon

ConcurrentModificationException in Java with Examples

Last Updated : 02 Apr, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
ConcurrentModificationException in Multi threaded environment In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown.
  1. If this exception is detected, then the results of the iteration are undefined.
  2. Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators.
For example: If we are trying to modify any collection in the code using a thread, but some another thread is already using that collection, then this will not be allowed. ConcurrentModificationException in Single threaded environment Since, there is no guarantee that whenever this exception is raised, an object is been under concurrent modification by some different thread, this exception is also thrown in the single-threaded environment. If we invoke a sequence of methods on an object that violates its contract, then the object throws ConcurrentModificationException. For example: if while iterating over the collection, we directly try to modify that collection, then the given fail-fast iterator will throw this ConcurrentModificationException. Example: In the following code, an ArrayList is implemented. Then few values are added to it and few modifications are made over it while traversing, Java
// Java program to show // ConcurrentModificationException  import java.util.Iterator; import java.util.ArrayList;  public class modificationError {     public static void main(String args[])     {          // Creating an object of ArrayList Object         ArrayList<String> arr             = new ArrayList<String>();          arr.add("One");         arr.add("Two");         arr.add("Three");         arr.add("Four");          try {             // Printing the elements             System.out.println(                 "ArrayList: ");             Iterator<String> iter                 = arr.iterator();              while (iter.hasNext()) {                  System.out.print(iter.next()                                  + ", ");                  // ConcurrentModificationException                 // is raised here as an element                 // is added during the iteration                 System.out.println(                     "\n\nTrying to add"                     + " an element in "                     + "between iteration\n");                 arr.add("Five");             }         }         catch (Exception e) {             System.out.println(e);         }     } } 
Output:
  ArrayList:   One,     Trying to add an element in between iteration    java.util.ConcurrentModificationException  
How to avoid ConcurrentModificationException? To avoid this exception,
  • Simply we can do the modifications once the iteration is done, or
  • Implement the concept of the synchronized block or method
Example: Let’s see how to resolve this exception by simply changing the place of modification. Java
// Java program to show // ConcurrentModificationException  import java.util.Iterator; import java.util.ArrayList;  public class modificationError {     public static void main(String args[])     {          // Creating an object of ArrayList Object         ArrayList<String> arr             = new ArrayList<String>();          arr.add("One");         arr.add("Two");         arr.add("Three");         arr.add("Four");          try {             // Printing the elements             System.out.println(                 "ArrayList: ");             Iterator<String> iter                 = arr.iterator();              while (iter.hasNext()) {                 System.out.print(iter.next()                                  + ", ");             }              // No exception is raised as             // a modification is done             // after the iteration             System.out.println(                 "\n\nTrying to add"                 + " an element in "                 + "between iteration: "                 + arr.add("Five"));              // Printing the elements             System.out.println(                 "\nUpdated ArrayList: ");             iter = arr.iterator();              while (iter.hasNext()) {                 System.out.print(iter.next()                                  + ", ");             }         }         catch (Exception e) {             System.out.println(e);         }     } } 
Output:
  ArrayList:   One, Two, Three, Four,     Trying to add an element in between iteration: true    Updated ArrayList:   One, Two, Three, Four, Five,  
From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated.

Next Article
ConcurrentModificationException in Java with Examples

S

sanskar_bindal
Improve
Article Tags :
  • Java
  • Java-Exceptions
  • Java-Exception Handling
Practice Tags :
  • Java

Similar Reads

    How to Solve ConcurrentModificationException in Java?
    An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote fil
    4 min read
    How to Avoid ConcurrentModificationException in Java?
    ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections,  i.e whenever we try to modify an object concurrently without permission  ConcurrentModificationException occurs which is present in java.util package. Procedure: Some steps are requi
    4 min read
    ConcurrentLinkedDeque pop() method in Java with Examples
    The Java.util.ConcurrentLinkedDeque.pop() method in Java is used to pop an element from the ConcurrentLinkedDeque. The element is popped from the top of the ConcurrentLinkedDeque and is removed from the same.Syntax: ConcurrentLinkedDeque.pop() Parameters: The method does not take any parameters.Retu
    2 min read
    ConcurrentLinkedDeque push() method in Java with Examples
    The push() method of ConcurrentLinkedDeque class is an in-built function in Java which pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success an
    2 min read
    ConcurrentLinkedDeque remove() method in Java with Examples
    The java.util.concurrent.ConcurrentLinkedDeque.remove() is an in-built function in Java which is used to remove an element from this deque.Syntax: public E remove() or public boolean remove(Object o) Parameters: The first overload of this method does not accepts any parameter. However the second ove
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences