Java Exception Handling

Java Exception Handling – ConcurrentModificationException

Today we’ll bite off another morsel from our delicious and mildly satiating Java Exception Handling series with a close look at the java.util.ConcurrentModificationException. The java.util.ConcurrentModificationException is typically thrown when code attempts to modify a data collection while that collection is actively in use, such as being iterated.

We’ll take the time in this article to further explore the java.util.ConcurrentModificationException, looking at where it sits in the Java Exception Hierarchy, along with some simple, functional code samples that will illustrate common scenarios that java.util.ConcurrentModificationExceptions might occur, and how to prevent them. Let’s get to it!

The Technical Rundown

When Should You Use It?

As discussed in the introduction, the most typical scenario that might lead to a java.util.ConcurrentModificationException is when performing modifications on a collection object that is currently in use. To illustrate, in our example code we’ll be creating a basic ArrayList<> object, adding a few items to it, then iterating through the elements. Depending on how we build our application and, therefore, how we choose to perform any modifications during the iteration, we’ll see that the application will behave very differently.

To begin, let’s start with the full working code sample below. At the end of the sample block we’ll go through each section in more detail to see what’s going on:


To make our example a bit more realistic we’ve added a simple Book class with a few fields to store basic book information:

Our goal is to build a List collection of Books that we can iterate through, while simultaneously checking for a particular element in the list and proactively removing any matching book element from the list while the iteration continues. To accomplish this we start with the modifiedListExample() method:

As you can see, this method creates a new ArrayList<Book> object called library, adds a handful of Books to the list, then performs an advanced for loop on the library list. For each book element in the list we output the book info to the log, then also check if the current book element has a title of "Gone Girl", in which case we remove that element from the library list. Let’s execute this method and see what we get in the log output:

Everything was working fine at first, but after removing "Gone Girl" from the library list we ran into a problem and threw a java.util.ConcurrentModificationException. The reason for this is that the JVM couldn’t determine what element should’ve come next in our for loop, since, for example, the original fourth element ("His Dark Materials") is no longer where it should’ve been.

To fix this issue we can slightly modify how we perform our iteration of library elements and, instead of using an advanced for loop syntax as above, we can create a new Iterator<Book> object, which will serve as our means of iterating through elements and, most importantly, allow us to remove any matched book elements without affecting the iteration process.

Thus let’s take a look at the modifiedIteratorExample() method:

The big difference is the for loop using a new Iterator<Book> object, grabbed from the library.iterator() method. We then call the bookIterator.hasNext() method to check if another element exists, then retrieve it inside the loop with bookIterator.next(). Lastly, and most importantly, we are not calling library.remove() directly on the parent list object. Instead we use the bookIterator.remove() method, which allows us to safely remove the current element from the iterator, so the upcoming bookIterator.hasNext() and bookIterator.next() don’t fail and throw another java.util.ConcurrentModificationException.

The result is that our log output shows all books except the one we removed and skipped over:

It’s also worth noting that the above sample code is a bit verbose, just to better illustrate what’s going on with our iteration. We could almost entirely remove the for code block and use the following snippet instead, which uses a lambda expression to check each book element and perform a remove function if the title is what we’re filtering:

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring, Maven, log4j, Struts, Kotlin, Grails, Groovy, and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!