Search code examples
javabukkitconcurrentmodification

Getting Concurrent Modification Exception


I have no idea why I'm getting this error: error message

This is line 107 (for loop):

        for (Pair<UUID, UUID> pair : timeStopList) {

           if (pair.getA() == playerUUID) {

              cancelTimeStop(pair.getB());

           }

        }

I hate to ask what might seem like such a simple solution but I really have no idea whats going on! So I would appreciate it that if you know the answer you could tell me. Thanks!

Code for cancelTimeStop:

    public static void cancelTimeStop(UUID entityUUID) {

    Entity unknownEntity = Bukkit.getEntity(entityUUID);

    if (unknownEntity == null || unknownEntity.isDead()) return;

    LivingEntity entity = (LivingEntity) unknownEntity;

    entity.removePotionEffect(PotionEffectType.SLOW);
    entity.removePotionEffect(PotionEffectType.BLINDNESS);

    entity.setGravity(true);
    entity.setAI(true);
    entity.setCanPickupItems(true);
    entity.setSilent(false);

    removeEntityFromTimeStop(entityUUID);

}

removeEntityFromTimeStop() is:

    private static void removeEntityFromTimeStop(UUID entityUUID) {

    if (timeStopList == null) return;

    timeStopList.removeIf(pair -> pair.getB() == entityUUID);

}

Solution

  • You can change slightly your for loop to avoid this exception:

    Pair<UUID, UUID> pairToRemove = null;
    for (Pair<UUID, UUID> pair : timeStopList) {
        if (pair.getA() == playerUUID) {
            pairToRemove = pair; // assign the found pair to pairToRemove variable
            break;
        }
    }
    if (pairToRemove != null) {
        cancelTimeStop(pairToRemove.getB());
    }
    

    UPDATE

    P.S. I made the assumption that once a pair.getA() == playerUUID is found there is no need to continue the loop. If there are multiple chances that this if statement evaluates to true then you can adjust the code to:

    List<Pair<UUID, UUID>> pairToRemoveList = new ArrayList();
    for (Pair<UUID, UUID> pair : timeStopList) {
        if (pair.getA() == playerUUID) {
            pairToRemoveList.add(pair);
        }
    }
    if (!pairToRemoveList.isEmpty()) {
        for (Pair<UUID, UUID> pair : pairToRemoveList) {
            cancelTimeStop(pair.getB());
        }
    }