简体   繁体   中英

HashMap Concurrent Modification

I am trying to check the server's entities and iterate trough them each second, and if I find one who is not spawned anymore,it will respawn automatically.

The problem occurs when, in my EntitySpawnEvent I remove the old entity from the hashmap and add a new one, this creating a java.util.ConcurrentModificationException . Is there any possibility I can least suppress this errors? (Because I am removing an Entity that the "check" already passed through.)

new BukkitRunnable() {
        public void run() {
            for(Entity e : CheckAliveEntities.keySet()) {
                if(!(e.isValid())) {
                        if(!(e instanceof Player)) {
                            System.out.println("DA");
                            x.removeHologram(e);
                            y.setEntityRespawn(e);
                            break;
                        }
                }
            }
        }       
    }.runTaskTimer(this, 5, 5);

You can use iterator for removing entities that you detect for removing.

new BukkitRunnable() {
    public void run() {
        for(Iterator<Entity> it = CheckAliveEntities.keySet().iterator(); it.hasNext();) {
            Entity e = it.next();
            if ( !e.isValid() && !(e instanceof Player) ) {
                        System.out.println("DA");
                        x.removeHologram(e); // needs refactoring
                        it.remove();
                        y.setEntityRespawn(e); // needs refactoring
                        break;
                    }
            }
        }
    }       
}.runTaskTimer(this, 5, 5);

I'm not sure whether it's removeHologram() or setEntityRespawn() is removing the entity. In any case, I would refactor the logic so that you can remove the entity in the for loop itself. Although you do have option to pass iterator itself to these methods, and call it.remove() in there.

If you have multiple BukkitRunnable threads running, and they all have access to same HashMap, then it's advisable to use ConcurrentHashMap implementation for CheckAliveEntities. Please see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM