I am currently working on a little project for school which is a TowerDefense game.
When initializing the game, it starts a Thread that calculates everything. After starting that Thread, my code jumps into a loop, that loops my graphics code. I think that it is using 2 Threads then. One thread is for calculating and the other one is the "standard" Thread, that is used when you open the program itself.
Now I wanted to add Projectiles to my Towers. For that I need to add a new Projectile Object to my Entity ArrayList. and whenever I try to do so it says
Exception in thread "main" java.util.ConcurrentModificationException
and points to the line where my graphicsloop is, that tries to loop my Entity Array. That makes sense, because my graphicsloop tries to read while my Projectiles are added to this Array. I tried to work with "synchronized" and I think I know how to use it and what it is for, but Im not that sure where I would use it in my code. I try to solve this problem since yesterday and couldnt find anything on the Internet how to solve it. Also Im not sure what piece of Code helps you, if you didnt understand exactly how my program works and what the problem is so if you need anything, feel free to ask.
Would be awesome, if someone could help me solving this problem and I already want to thank you, if you are still reading
edit: I think these are the important pieces of code:
World update method:
private void updateRunning() {
waveTimer();
for (Entity e : entities) {
if (e.isMonster() && !block) {
e.toMonster().move();
if (e.toMonster().getHealth() <= 0)
entities.remove(e);
} else if (e.isTower()) {
e.toTower().setTarget(e.toTower().findTarget());
e.toTower().shoot();
} else if (e.isProjectile()) {
e.toProjectile().update();
}
}
}
Renderer loop method:
private void updateRunning() {
cam.update();
for (Entity ent : world.getEntities()) {
ent.draw();
}
cursor.update();
cursor.draw(); // Must always be on bottom draw-methods, to be drawed
// on top of
// everything else
cam.refresh();
}
edit2
private void addWave() {
if (wave % 3 == 1) {
for (int i = 0; i < 6; i++) {
entities.add(new Monster(this, i + 1, path.getCoord(0).x,
path.getCoord(0).y - i * 57, 0.35f, Assetloader.monster01));
}
} else if (wave % 3 == 2) {
} else {
}
}
private void attack(Monster target, float damage) {
world.addEntity(new Projectile(world, vec.x, vec.y, 20, 20, target,
this, Assetloader.cursor01));
ready = false;
lastShot = System.currentTimeMillis();
}
public void addEntity(Entity e) {
this.entities.add(e);
}