ConcurrentModificationException when adding to ArrayList in getter

506
March 01, 2017, at 03:11 AM

The following code gives a ConcurrentModificationException, particular the escaped lines and I'm wondering why. I have found that this can happen when you add to a list after an iterator has been extraced or when two threads access the list at the same time. However I don't think this is the case in my example.

What I am doing is passing the GameObjects list as a parameter:

camera.render(g, map.getGameObjectHandler().getGameObjects());

Getter:

    public ArrayList<GameObject> getGameObjects() {
//          if (player != null) {
//              gameObjects.add(player);
//          }
        return this.gameObjects;

I am later iterating over the listbut not removing or adding anything. I'm only accesing each element after another using an Iterator.

I hope that I provided enough information and will gladly provide more if needed.

Thanks in advance.

//EDIT:

I think the problem was adding the player to the list each time the getter is called. I fixed it by adding the player to the list when he is spawned. But I would still like to know what I did wrong, because this isn't the root of the problem or is it ?

//Update:

The main loop looks basically like this:

map.update(); // iterating over the list and calling methods of objects in 
              // the list [running in main game thread]
repaint(); // calling paintComponentMethod where we pass our list as an 
           // argument so all its content can be drawn [running in event-
           // dispatch-thread !?]`
Answer 1

ConcurrentModificationException on an ArrayList can happen when:

  • a portion of code is both iterating and modifying the list,
  • there are concurrent modifications like add / remove while another thread is iterating on the list.
Rent Charter Buses Company
READ ALSO
Convert parametized Enum to Enumerated Annotation in android

Convert parametized Enum to Enumerated Annotation in android

I have a question regarding to the andriod @IntDef AnnotationI know that in its basic usage, it should replace the enum

473
Pasting/Replacing a character using mouse selection in Java textfield (with specified character limit)

Pasting/Replacing a character using mouse selection in Java textfield (with specified character limit)

I have extended DocumentFilter class to limit the number of characters to be entered to the specified number in text fieldHere's my SSCE:

413
XOR encryption with only uppercase

XOR encryption with only uppercase

Is there a way to receive only uppercase letters and digits from xor encryption? Or even better only uppercase letters? Or do I have to use something else?

496
How to restrict JFileChooser to only one file

How to restrict JFileChooser to only one file

I want to implement a save function into my program where a user can access a file that will come with the program, ie

380