How to deal with ConcurrentModificationException

后端 未结 3 652
深忆病人
深忆病人 2020-12-12 03:26

I am getting the a ConcurrentModificationException from my cooldown timer. I use a thread to reduce the values every second like this:

public class CoolDownT         


        
3条回答
  •  清歌不尽
    2020-12-12 04:19

    You can't modify collections when using a foreach loop.

    You can however iterate over the Map.entrySet() and do everything you need:

    public void run() {
        for (Iterator> i = playerCooldowns.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = i.next();
            entry.setValue(entry.getValue() - 20); // update via the Map.Entry
            if (entry.getValue() <= 0) {
                i.remove(); // remove via the iterator
            }
        }
    }
    

提交回复
热议问题