I keep getting java.util.concurrentmodificationexception.. How to fix this? - java

I've been working on this snippet of code. Here is the pseudocode of what I want to happen:
a.check if sections(which is a list) size is 0.
b.if sections size is 0, then automatically enroll the student to the section by calling sections.add(newSection)
c.else if sections size is not zero, check for conflicts with schedule
d.if there are no conflicts, then enroll the student to the section by calling sections.add(newSection)
e.else do nothing
Java keeps throwing "java.util.concurrentmodificationexception" error on me. I know, I'm not supposed to alter the size of the ArrayList while traversing the list because it will modify the iterator. Is there another way to solve this? :D
Thanks a lot.
Your help is highly appreciated. :)
public String enrollsTo(Section newSection){
StringBuffer result = new StringBuffer();
String resultNegative = "Failed to enroll in this section.";
String resultPositive = "Successfully enrolled in section: " + newSection.getSectionName() + ".";
int previousSectionSize = sections.size();
if(this.sections.isEmpty()){
this.sections.add(newSection);
result.append(resultPositive);
}else{
for(Iterator<Section> iterator = sections.iterator(); iterator.hasNext() ; ){
Section thisSection = iterator.next();
if(thisSection.conflictsDayWith(newSection)==false &&
thisSection.conflictsTimeWith(newSection)==false){
this.sections.add(newSection); //<-- i believe the problem lies here.
result.append(resultPositive);
}
}
}
// if(this.sections.size() == previousSectionSize){
// result.append(resultNegative);
// }
return result.toString();
}

Don't do sections.add(newSection) inside your for loop, as this is a modification of the collection you're currently iterating over.
Also, don't you want to check all sections before deciding whether to add the newSection or not? Maybe something like this:
boolean conflict = false;
for (...) {
if (/* check for conflict */) {
conflict = true;
break;
}
}
if (!conflict) {
sections.add(newSection);
}

From the javadoc for ConcurrentModificationException (my emphasis):
This exception may be thrown by methods that have detected concurrent
modification of an object when such modification is not permissible.
For example, it is not generally permissible for one thread to modify
a Collection while another thread is iterating over it. In general,
the results of the iteration are undefined under these circumstances.
Some Iterator implementations (including those of all the general
purpose collection implementations provided by the JRE) may choose to
throw this exception if this behavior is detected. Iterators that do
this are known as fail-fast iterators, as they fail quickly and
cleanly, rather that risking arbitrary, non-deterministic behavior at
an undetermined time in the future.
Note that this exception does not always indicate that an object has
been concurrently modified by a different thread. If a single thread
issues a sequence of method invocations that violates the contract of
an object, the object may throw this exception. For example, if a
thread modifies a collection directly while it is iterating over the
collection with a fail-fast iterator, the iterator will throw this
exception.
Note that fail-fast behavior cannot be guaranteed as it is, generally
speaking, impossible to make any hard guarantees in the presence of
unsynchronized concurrent modification. Fail-fast operations throw
ConcurrentModificationException on a best-effort basis. Therefore, it
would be wrong to write a program that depended on this exception for
its correctness: ConcurrentModificationException should be used only
to detect bugs.
Potential solution: instead of adding directly to the list you're iterating, add to a temporary list and then when you've finished iterating, do an addAll().

While iterating collection, you can't modify it. The line this.sections.add(newSection); throwing the exception. You may need to use some boolean marker to check the condition
if(thisSection.conflictsDayWith(newSection)==false &&
thisSection.conflictsTimeWith(newSection)==false)
After the for loop if your boolean marker is true, then you can write
this.sections.add(newSection);
result.append(resultPositive);

You're correct in your assumption,
this.sections.add(newSection);
is definitely the source of your problem.
Simplest solution: Have a boolean representing the section's availability. Start out assuming it is available. If there is any conflict in your iterator, set it to false. After the iterator, add the section if the section is available (boolean true).

ConcurrentModificationExceptions often occur when you are modifying a collection while you are iterating over its elements. Read this tutorial for more details and this old SO post Why does it.next() throw java.util.ConcurrentModificationException?

I agree with #sudocode that you don't want to be adding the newSection every time you find even a section which doesn't conflict. I would have thought that when you step through the code in your debugger this would be apparent. ;)
BTW another (more obscure) way to do this without a flag is
CHECK: {
for (...) {
if (/* check for conflict */)
break CHECK;
}
sections.add(newSection);
}

Related

JAVA java.util.ConcurrentModificationException

I am trying to create simple JAVA program. But since last day, I am having this issue, I cannot fix.
public void receiveUpdate(ArrayList<Connection> connections) {
for(Connection senderConnection : connections) {
for(Connection receiverConnection : this.connections) {
if(senderConnection.getDestination() == receiverConnection.getDestination()) {
if(senderConnection.getDistance() + 1 < receiverConnection.getDistance()) {
senderConnection.setEnabled(false);
senderConnection.setDistance(senderConnection.getDistance() + 1);
this.connections.remove(receiverConnection);
this.connections.add(senderConnection);
}
}
}
senderConnection.setEnabled(false);
senderConnection.setDistance(senderConnection.getDistance() + 1);
this.connections.add(senderConnection);
}
}
In this method I always get error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at router.Router.receiveUpdate(Router.java:56)
at router.Router.sendUpdate(Router.java:49)
at loader.Loader.notifyNetworkChanges(Loader.java:61)
at loader.Loader.main(Loader.java:102)
I have noticed, that exception doesn't appear if I comment block:
senderConnection.setEnabled(false);
senderConnection.setDistance(senderConnection.getDistance() + 1);
this.connections.add(senderConnection);
Can anyone tell me, where is the problem?
ConcurrentModificationException This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
The problem is here
this.connections.remove(receiverConnection);
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
Check this out
To solve your problem you need to use Iterator and remove() method like this
Iterator<String> connectionsIterator = connections.iterator();
while (connectionsIterator.hasNext()) {
if (senderConnection.getDistance() + 1 < receiverConnection.getDistance()){
connectionsIterator.remove();
// add the connection to another list other than this.connections.add(senderConnection);
// then when you finish add them back the this.connections
// so you avoid modifying this.connections
}
}
You are actually modifying the collections, while iterating.
this.connections.remove(receiverConnection);
this.connections.add(senderConnection);
Use an Iterator and call remove():
Iterator<String> iter = connections.iterator();
while (iter.hasNext()) {
if (someCondition)
iter.remove();
}
Use Iterator remove method instead of ArrayList
If you are modifying (eg deleting from) the same list you are looping then you are bound to get the ConcurrentModificationException
You can either use an iterator as #ankur-singhal mentioned or make a deep copy of the list and remove from that copy. Then you can assign the reference of the original list to point to the new one that has the modifications.
Another "greedy" approach (but without using iterators) would be to keep all items to be removed in another new list and after ending your for loop then call removeAll(listOfConnectionsToBeRemoved), for example:
before your for loops
ArrayList<Connection> connectionsToBeRemoved = new ArrayList<Connection>();
inside your for loops
connectionsToBeRemoved.add(receiverConnection)
after ending your for loops
this.connections.removeAll(connectionsToBeRemoved)
*you may do the same for connections to be added. Keep them in a new list and then add them all to your connection list.
You are looping through this.connections and inside you are trying to remove from this.connections this will java.util.ConcurrentModificationException. Change your code to use iterator.

How to Redesigning a method in order for it to work

My code results in an java.util.ConcurrentModificationException error. Here is the following code.
Here is the exact error:
java.util.ConcurrentModificationException
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
at java.util.HashMap$KeyIterator.next(HashMap.java:928)
at ca.on.oicr.pinery.lims.gsle.GsleClient.getOrders(GsleClient.java:720)
Line 720 is the second for loop
I posted this question before and was told that "You're adding to orders inside a loop that's looping over the elements of orders, that's what causes the exception. Don't modify a collection you're looping over inside the loop. Likewise with samples". I understand that I to re construct this method and received the following suggestions.
ListIterator<Order> it = orders.listIterator();
while ( it.hasNext() ) {
Order ord = it.next();
if ( ) // some condition
it.remove(); // This wil remove the element that we just got using the next() method
if ( ) // some other condition
it.add(new Order()); // THis inserts the element immediately before the next call to next()
}
Now I am stuck at how to do the adding of the samples and the order when using the iteration method since you would iterate differently though a set, I assume I would use a for loop.
This is the part I am getting confused on how to change in order to not get the java.util.ConcurrentModificationException.
f
So far I have gotten up to here.
java.util.ListIterator<Order> it = orders.listIterator();
while (it.hasNext()) {
it.next().getId();
if (sampleOrderMap.containsKey((it.next().getId())))
{
Set<OrderSample> samples = sampleOrderMap.get(it.next().getId());
}
}`
I just do not know how to put in the rest in a way that I would not get the ConcurrentModificationException
From Java Docs:
ConcurrentModificationException may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.
To go around this, you can create a temporary collection to add to other than the one you are iterating through.
Then, after you finish iterating, you can use orders.AddAll(tempCollection) to add the new items.

How to simulate ConcurrentModificationException in own class?

I have been reading "Effective Java" Item 60, which is "Favor the use of standard exceptions".
Another general-purpose exception worth knowing about is ConcurrentModificationException. This exception should be thrown if an object that was designed for use by a single thread or with external synchronization detects that it is being concurrently modified.
Normally people face with CME when they try remove from a collection while looping.
But in here I am interested about what would be a concise example on detecting a concurrent modification on self-implemented class object?
I expect it to be something like synchronizing on internal object and related boolean flag, if another thread confronts the flag being false, then throwing exception.
For a simple research I have found in source of ArrayList:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
but the principle behind how modCount is maintained. I cannot find where it is being decremented.
The modification count is essentially the "revision number" of the collection's state. It is incremented every time there is a structural change to the collection. It is never decremented.
When starting iteration, the iterator remembers the value of the mod count. It then periodically checks that the container's current mod count still equals the remembered value. If it doesn't -- meaning there has been a structural change since iteration began -- a ConcurrentModificationException is thrown.
As for how you would implement this kind of behaviour yourself: Your class depends on some assumptions to work properly, which could be violated if access to an object is not synchronized properly. Try to check those assumptions and throw a CME if you find that they are not true.
In the example of ArrayList, the assumption is that nobody will change the structure of the list while you are iterating over it, so ArrayList keeps track of a modification count that is not supposed to change during an iteration.
However, this checking is only there to make it more likely that a bad access will cause a clean exception instead of weird behaviour - in other words, this exception is just a help to developers and does not need to enforce correctness, because correctness is already compromised when you encounter it.
It is a good idea to offer this kind of help where it does not impact the performance of your class much, but using e.g. synchronization to ensure correct use is probably a bad idea - then you might as well make the class threadsafe to begin with.
This is why the API documentation for ArrayList says:
Note that the fail-fast behavior of an iterator cannot be guaranteed
as it is, generally speaking, impossible to make any hard guarantees
in the presence of unsynchronized concurrent modification. Fail-fast
iterators throw ConcurrentModificationException on a best-effort
basis. Therefore, it would be wrong to write a program that depended
on this exception for its correctness: the fail-fast behavior of
iterators should be used only to detect bugs.
So, the general approach is following: just remember current state of your object and check its state every time when trying to access the object, if state changed, throw your exception!

Concurrent modification error when adding elements to LinkedList

I have an List of LinkedList objects.
List<LinkedList<File1>> backup = new ArrayList<LinkedList<File1>>();
The LinkedList contains some elements. I need to add additional elements dynamically by clicking a button. While doing this, I'm getting a concurrent modification error. I really don't understand why this error is popping up. Here is the code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)
{
// When JOIN button is clicked
int parent_node,dist_node;
// List<File1> temp_list = new ArrayList<File1>();
File1 f_new = new File1();
parent_node = Integer.parseInt(jTextField4.getText());
dist_node = Integer.parseInt(jTextField5.getText());
LinkedList<File1> tmp_bk = backup.get(parent_node);
System.out.println("parent node : " + parent_node);
System.out.println("dist node : " + dist_node);
System.out.println("no of lists : " + backup.size());
f_new.nod = backup.size();
f_new.dist = dist_node;
// temp_list.add(f_new);
tmp_bk.add(f_new);
ListIterator itr = it_bk.get(parent_node);
while(itr.hasNext())
{
File1 f = (File1)itr.next();
System.out.println("NODE : " + f.nod + "DIST : " + f.dist);
}
}
It's probably because you're editing the list, then trying to use the original iterators. The collections API doesn't allow that. You need to create new iterators after editing the list.
For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
First, if you really expect people to give their attention to your question, you should do them the favor of asking it clearly and in standard English.
Second, you should provide an indication of exactly where in your code you're getting the ConcurrentModificationError.
Finally, what is it_bk? It just shows up in your code without any explanation. If it is an ArrayList of ListIterators it is certainly possible that its parent_node-th element is in a state where it isn't sure that hasNext() or next() will be safe. I'm guessing you modified the underlying collection with your tmp_bk.add(f_new); and so a pre-existing iterator is worried that its invariants may be violated.
General advice: Don't create and retain iterators (or collections of them). When you want an Iterator, create it, use it, and abandon it.
java.lang.Colletions from JDK 1.5 is not synchronized. In earlier version(jdk 1.4), you wont find this problem.
There are multiple solutions available for these problem and you need to choose one of them wisely as per your use case.
Solution 1: The list can be converted to an array with list.toArray() and iterate on the array. This approach is not recommended if the list is large.
Answer 2: The entire list can be locked while iterating by wrapping your code within a synchronized block. This approach adversely affects scalability of your application if it is highly concurrent.
Answer 3: JDK 1.5 gives you ConcurrentHashMap and CopyOnWriteArrayList classes, which provide much better scalability and the iterator returned by ConcurrentHashMap.iterator() will not throw ConcurrentModificationException while preserving thread-safety.
Answer 4: Remove the current object via the Iterator “it” which has a reference to the underlying collection “myStr”. The Iterator object provides it.remove() method for this purpose.

Problems with ListIterator and Concurrent Modification Exception

I have two ArrayLists, each holding blocks of certain size: blockList, eraserList. Blocks are objects with two fields: start and end. I need to subtract one set of blocks from the other set of blocks.
I must walk through the eraserList and "erase" blocks out of the blockList where they overlap. Thus my code looks like:
void eraseBlocks (Arrylist<Blocks> blockList, ArrayList<Blocks> eraserList) {
ListIterator<Blocks> it = blockList.listIterator();
for (Blocks eraser: eraserList) {
while (it.hasNext()) {
Blocks block= it.next();
if ((eraser.start <= block.start) && (eraser.end >= block.end))
blockList.remove(block);
else if ((eraser.start <= block.start) && (eraser.end < block.end)){
block.set(start, eraser.end);
else if () {
...
//more code for where the eraser partially erases the beginning, end, or splits the block
//if statements call the .add(), .set(), and remove() methods on the blockList.
...
}
}
}
I don't understand why I am getting a Concurrent Modification Exception. I never modify the eraserList.
I am trying to modify the block object that is assigned in the "Block block = it.next();" statement. I am also modifying the blockList by removing or adding blocks to the list. I thought the whole point of the ListIterator was that it allowed you to modify, add, or subtract a list you are walking through.
The Failure Trace points to the Blocks eraser = it.next(); as the line drawing the exception, but I don't know what that is telling me.
Can anyone help me figure out what I am doing wrong?
Thanks!
Yes, ListIterator is designed to allow the modification of the list. But you are not using the remove() method of the ListIterator, but directly manipulate the underlying list itself.
Replace
blockList.remove(block);
with
it.remove();
If you remove an element another way, you can get a CME.
You need to call remove() on the Iterator, not on the List.
From the javadoc:
If a single thread issues a sequence of method invocations that
violates the contract of an object, the object may throw this
exception. For example, if a thread modifies a collection directly
while it is iterating over the collection with a fail-fast iterator,
the iterator will thow this exception.

Categories

Resources