We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello!
I am hooking up my electric piano to processing using The MidiBus library. I'm basically playing around with visualising the notes played in different ways. This often includes adding some sort of object to an array or arraylist and then iterating through the list to call .update() which updates position, size etc for the object and draws it on the canvas.
However I often get the problem of "concurrent modification exception". I do not get this error when I run the code without the pian but just randomly call the note-pressed function. After some googling this leads me to believe that the error stems from me sometimes calling the notePressed() function, which creates a new object and add to the list, right in the middle of the update loop. Hence I am modifying the list whilst I am iterating over it.
So with that long introduction, here is my question:
Is there a way for me to tell processing "Call this function as soon as possible, but wait until next iteration of draw()"?
or alternativley : "Excecute this block of code without any interruption" ?
From my few qourses in Java i vaguely recall this issue beeing about synchronization, am I right?
Appreciate any help! :)
Answers
Previous relevant posts: https://forum.processing.org/two/search?Search=synchronize
Kf
If 1 Thread is busy traversing an Iterable container in a
for ( : ) {}
loop, and another Thread happens to modify that container's size() at that same moment, we get a ConcurrentModificationException! :-SSThe most efficient way to avoid that is to move that kinda code around to make sure only 1 Thread is responsible to iterate over a container & mutate its size(), and no other. :-B
Better to use a collection that's defined for passing information from one thread to the other rather than using synchronization here.
Import and swap out your ArrayList for eg. ConcurrentLinkedQueue Iterating should work correctly, although better to use
poll()
as it will remove the items as you go.