Synchronizing doesn't do anything to prevent the ConcurrentModificationException
if the synchronized code modifies the collection during iteration, which you do here:
for (GatewayMsg msg : PacketQueue){
PacketQueue.remove(msg); // <== Not allowed during iteration
packetHandler.onPacket(msg);
}
During an iteration, you may only remove elements via an Iterator
, e.g.:
Iterator<GatewayMsg> it = PacketQueue.iterator();
while (it.hasNext()) {
GatewayMsg msg = it.next();
it.remove(); // <== This is allowed, provided the collection supports it
packetHandler.onPacket(msg);
}