Hey.
I have a HashMap like this:
HashMap<Player, Integer> players = new HashMap<Player, Integer>();
The int is for the amount of seconds the player has left. Each second one second is removed from the person: (this is inside a thread)
for (final Iterator<Player> it = players.keySet().iterator(); it.hasNext(); ) { final Player player = it.next(); if (player.isOnline()) { int seconds = getTimeLeft(player); if (seconds <= 0) { if (!(player.isDead())) { player.setHealth(0); // This kills the player } } setTimeLeft(player, --seconds); } else { it.remove(); } }
If the player has 0 seconds or less, the player is killed and later runs a method to update everything correspondingly. The player can also die naturally, either by another player or from eg. starvation, so thats why I can't necessarily add the check directly to the thread / loop. This is the code which is run when the player dies:
public void playerKilled(Player player) { // Some validation before this players.remove(player); spectators.add(player); }
The problem with this is that it always throws a ConcurrentModificationException. I changed the HashMap to ConcurrentHashMap and that fixed it, but that forces me add a ton of null checks everywhere and it ends up extremely ugly and occasionally fails for some reason.
So the question is: What would be the best solution to avoid both of these errors while retaining the functionality?