[SPIGOT-7999] ConcurrentModificationException in EntityLiving#hurtServer Created: 28/Jan/25  Updated: 09/Mar/25  Resolved: 09/Mar/25

Status: Resolved
Project: Spigot
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Tau Assignee: Unassigned
Resolution: Fixed Votes: 0
Labels: bug
Environment:

Windows 10 x86_x64


Version: This server is running CraftBukkit version 4430-Spigot-d421948-d20d4c1 (MC: 1.21.4) (Implementing API version 1.21.4-R0.1-SNAPSHOT)
Guidelines Read: Yes

 Description   

A ConcurrentModificationException is thrown when modifying the potion effects of a LivingEntity on CreatureSpawnEvent when mobs are spawned due to a mob effect.

This is due to this code in in EntityLiving#hurtServer:

                Iterator iterator = this.getActiveEffects().iterator();

                while (iterator.hasNext()) {
                    MobEffect mobeffect = (MobEffect) iterator.next();

                    mobeffect.onMobHurt(worldserver, this, damagesource, f);
                }

As MobEffect#onMobHurt spawns the mob (such as a sliverfish for the infested effect), it then calls CreatureSpawnEvent and (and our event handler) while iterating. When our plugin removes an effect, the next iteration throws the error.

The plugin code:

    @EventHandler
    public void onCreatureSpawn(CreatureSpawnEvent e) {
        if (e.getEntityType() == EntityType.SILVERFISH) {
            e.getLocation().getWorld().getNearbyEntities(e.getLocation(), 1, 1, 1).stream()
                    .filter(ent -> ent instanceof Player)
                    .map(ent -> (Player) ent)
                    .filter(ent -> ent.hasPotionEffect(PotionEffectType.INFESTED))
                    .findAny()
                    .ifPresent(ent -> ent.removePotionEffect(PotionEffectType.INFESTED));
        }
    }

Generated at Tue Apr 22 06:38:56 UTC 2025 using Jira 10.3.5#10030005-sha1:190c783f2bd6c69cd5accdb70f97e48812a78d14.