Here is my class with two methods modifying the List PacketQueue
. These two methods are execute in two thread, so synchronize
is tagged.
public class MessageHandler implements nuctrl.interfaces.MessageHandler, Runnable {
private static final List<GatewayMsg> PacketQueue = new LinkedList<GatewayMsg>();
@Override
public void insert(GatewayMsg msg) {
synchronized (PacketQueue){
PacketQueue.add(msg);
PacketQueue.notify();
}
log.debug("insert " + msg.toString());
}
@Override
public void run() {
while(running){
synchronized (PacketQueue){
try {
while(PacketQueue.size() == 0){
PacketQueue.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
for (GatewayMsg msg : PacketQueue){
PacketQueue.remove(msg);
packetHandler.onPacket(msg);//method call
}
}
}
}
}
run()
is for thread-4 and insert()
is for another thread(I/O Worker #1). Synchronized
has been added, and everything seems ok, but I still kept getting ConcurrentModificationException.
DEBUG [New I/O worker #1] (MessageHandler.java:47)| insert GatewayMsg<>
Exception in thread "Thread-4" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:761)
at java.util.LinkedList$ListItr.next(LinkedList.java:696)
at nuctrl.core.MessageHandler.run(MessageHandler.java:67)
at java.lang.Thread.run(Thread.java:680)
It drives me crazy now! Can anyone help find the fault? Or other ways to do the same thing?