How To Avoid And Resolve ConcurrentModificationException in Java And Groovy

Posted By : Ankit Nigam | 03-Feb-2014
Hello Friends,
Most of us are very familiar with this annoying error that keeps on coming when we are dealing with Lists/ArrayList and iterating over it as well as removing the elements on the same List/ArrayList.
The basic reason behind throwing this ConcurrentModificationException at Runtime is related to the behaviour of the JVM , which does not let one thread to delete an element of the list while any other thread is iterating over it.When these types of iterations are done the resuts can not be defines.It leads to an undeterministic situation so iterators are defined to throw ConcurrentModificationException in this situation.These iterators do not take risks by executing these conditions & throw the exception right away & thus are called Fail-Fast Iterators.
 
Let us suppose an instance from Groovy itself.We have 2 domains User & Question.

Class User{
	String username
	String password
	static hasMany = [questions : Question]
	static constraints = {		
		username nullable: false
		password nullable: false
	}
} 

Class Question{
	String content
	boolean isValid = false
	static belongsTo = [user : User]
	static constraints = {		
		content nullable: false
	}
} 

Now In Groovy If we want to delete all the Questions which are having isValid set to false then everyone would have simply written

def currentUser = springSecurityService.currrentUser
def questionList = Question.findAllByUserAndIsValid(currentUser,false)
questionList.each{
	currentUser.removeFromQuestions(it)
	it.delete(flush : true)
}

But this will throw the ConcurrentModificationException as we are using iterator here i.e. each closure & traversing-deleting the same list.
 
Solution:
In order to resolve & avoid the ConcurrentModificationException what we can do is to prevent the use of List/ArrayList for these situations & conveting the List to an Array as JVM traverse the array using indices not iterator.
No this code will remove the ConcurrentModificationException exception to occur.
def currentUser = springSecurityService.currrentUser
def questionList = Question.findAllByUserAndIsValid(currentUser,false)
		Question[] ques = questionList.toArray(new Question[questionList.size()]);
		for(int i=0;i< ques.length ;i++){
		currentUser.removeFromQuestions(ques[i])
		ques[i].delete(flush : true)
		}

For simple use in Java , you can convert the List into Array using the following code :

List<Type> list = ..;
Type[] array = list.toArray(new Type[list.size()]); 

Now enjoy the power of Java & Groovy

 
Thanks,
Ankit

About Author

Author Image
Ankit Nigam

Ankit has worked on development of various SaaS applications using Grails technologies. He has good exposure on FFMPEG and video content management applications. Ankit likes mobile gaming and going out with friends.

Request for Proposal

Name is required

Comment is required

Sending message..