Tuesday, 15 September 2015

java - Is this solution to ConcurrentModificationException safe? -



java - Is this solution to ConcurrentModificationException safe? -

i have 2nd thread utilize send messages using osc. main thread add together messages, had problem concurrentmodificationexception.

what did prepare made new list messages add. in 2nd thread add together messages list want send.

at moment runs without problems, i'm wondering luck? in other words, alter run concurrentmodificationexception still there little or did prepare problem?

public void run() { while (running) { tosend.addall(newmessages); newmessages.clear(); iterator<oscprioritymessage> itr = tosend.iterator(); while (itr.hasnext()) { oscprioritymessage msg = itr.next(); oscp5.send(msg, netaddress); itr.remove(); } seek { sleep((long)(waittime)); } grab (exception e) { } } }

here add together messages send:

public void send(oscprioritymessage msg) { newmessages.add(msg); }

you still need synchronize on newmessages whereever access it. 2 places see here 1) adding , 2) copying tosend , clearing it. maybe there more.

public void send(oscprioritymessage msg) { synchronized(newmessages){ newmessages.add(msg); } }

to create clear tosend temporary, local list utilize in sending process, declare local variable.

instead of

tosend.addall(newmessages); newmessages.clear();

you can do

arraylist<oscprioritymessage> tosend; synchronized(newmessages){ tosend = new arraylist<>(newmessages); newmessages.clear(); }

without synchronization might miss messages (or them twice, or maybe weird) beingness added concurrently.

now have fresh tosend in every loop iteration, don't need remove elements anymore , can away whole iterator, replacing simple loop:

for (oscprioritymessage msg: tosend){ oscp5.send(msg, netaddress); }

and finally, @dlev suggests, take @ existing thread-safe queue implementations in java.util.concurrent package.

java multithreading concurrentmodification

No comments:

Post a Comment