I have a synchronized method called getChunks(). This is the only way the set of chunks are called in the whole program, yet when iterating through them (by calling getChunks()) I get a concurrentModificationException. This would be because the ChunkManager class, which runs in a seperate thread, would have generated a new chunk. But the only way it accesses the chunks is though getChunks()...
The getChunks() method:
public synchronized Set<WorldChunk> getChunks() {
return chunks;
}
The render() method, where the exception occurs
public void render() {
for(WorldChunk wc : chunkMap.getChunks()) { // <-- This is the line where the exception occurs
wc.render();
}
}
The ChunkManager Class
public class ChunkManager implements Runnable {
private static final int CHUNK_UPDATE_DELAY_MILLIS = 100;
private ChunkMap chunkMap;
public ChunkManager(ChunkMap chunkMap) {
this.chunkMap = chunkMap;
new Thread(this).start();
}
@Override
public void run() {
while(true) {
manageChunks();
}
}
private void manageChunks() {
int cx = (int) ((Camera.getX() + WorldChunk.CHUNK_WIDTH / 2) / WorldChunk.CHUNK_WIDTH);
int cz = (int) ((Camera.getZ() + WorldChunk.CHUNK_DEPTH / 2) / WorldChunk.CHUNK_DEPTH);
int renderDistance = 2;
for(int icx = cx - renderDistance; icx < cx + renderDistance; icx++) {
for(int icz = cz - renderDistance; icz < cz + renderDistance; icz++) {
if(!chunkMap.hasChunk(icx, icz)) {
chunkMap.genChunk(icx, icz, false);
}
}
}
for(WorldChunk wc : chunkMap.getChunks()) {
if((Math.abs(wc.getX() - Camera.getX()) + Math.abs(wc.getZ() - Camera.getZ())) > WorldChunk.CHUNK_WIDTH + WorldChunk.CHUNK_DEPTH) {
wc.unload();
}
}
try {
Thread.sleep(CHUNK_UPDATE_DELAY_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
EDIT StackTrace:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
at java.util.HashMap$KeyIterator.next(HashMap.java:928)
at java.util.AbstractCollection.addAll(AbstractCollection.java:333)
at java.util.HashSet.<init>(HashSet.java:117)
at com.ryxuma.kalidus.world.World.render(World.java:35)
at com.ryxuma.kalidus.Core.renderPerspective(Core.java:35)
at org.heatstroke.Heatstroke$Runner.run(Heatstroke.java:365)
at org.heatstroke.Heatstroke.start(Heatstroke.java:124)
at com.ryxuma.kalidus.Core.main(Core.java:60)