简体   繁体   English

并发修改异常迭代

[英]concurrent modification exception iterations

I did a research about it and tried fixing this exception by changing my collections and for loops to iterators but that doesn't seem to fix it. 我对此进行了研究,并尝试通过更改集合和迭代器的for循环来修复此异常,但这似乎无法解决。 I still get the same error. 我仍然遇到相同的错误。

He are the error logs from eclipse: https://imgur.com/a/uqULZsw 他是来自eclipse的错误日志: https : //imgur.com/a/uqULZsw

Here is my removeTarget function from the file BountyHunterController 这是我来自文件BountyHunterController的removeTarget函数

public void removeTarget(Player player) {

    player.getTemporaryAttributtes().remove(TARGET_IDENTIFIER);
    player.getPackets().sendIComponentText(1296, 25, "None");

    Iterator<Player> iterator = getPlayers().iterator();
    while (iterator.hasNext()) {
        Player p = iterator.next();
        Optional<Player> targ = minigame.getTarget(p);
        if (targ.isPresent()) {
            if (targ.get().getUsername().equalsIgnoreCase(player.getUsername())) {
                p.getTemporaryAttributtes().remove(TARGET_IDENTIFIER);
                p.getPackets().sendIComponentText(1296, 25, "None");
                p.sendMessage("<col=FE1212>Your target has left, and you will be assigned another one.");
                Controler con = p.getControlerManager().getControler();
                if (con != null) {
                    if (con instanceof BountyHunterController) {
                        BountyHunterController bh = (BountyHunterController) con;
                        minigame.map.remove(type, player);
                        bh.assignTarget();
                    }
                }
            }
        }
    }
    minigame.map.remove(type, player);
    return;
}

Here is the error in line 495 这是495行中的错误

Player p = iterator.next(); 播放器p = iterator.next();

Note: Attempt leave, and leave are just Boolean functions checking conditions, so the error is only from this function I provided. 注意:尝试离开和离开只是布尔函数检查条件,因此错误仅来自于我提供的此函数。

What am I doing wrong, and how could I solve this issue? 我在做什么错,我该如何解决这个问题?

It does not matter how you handle iterators: Either behind the scenes with a for loop or yourself if you ever edit the underlying data structure while it is in use this will happen. 处理迭代器的方式无关紧要:无论是使用for循环在后台运行,还是您自己在使用中编辑基础数据结构时,都会发生这种情况。

Ways to get around this are: 解决此问题的方法是:

1) If you can, don't use an iterator, access the elements using a counter. 1)如果可以,请不要使用迭代器,而应使用计数器访问元素。

For example: for a list iterator use: for(int i=0; i<player_list.size(); i++) {... and inside the loop: player = player_list.get(i) 例如:对于列表迭代器,请使用: for(int i=0; i<player_list.size(); i++) {...并在循环内: player = player_list.get(i)

2) Iterate over a copy of the data structure, but of course this means copying. 2)遍历数据结构的副本,但这当然意味着复制。

3) Keep tract of your edits and do them at the end. 3)保留您的编辑内容,并在最后进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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