简体   繁体   中英

Concurrent Modification Exception in Hashmap while using the same Hashmap in two threads

I am developing a multi-player snake game played over the network. It is running fine however it occasionally throws java.util.ConcurrentModification Exception. This is thrown in the main class of my game in the paintComponent() method. Code at which this is thrown is

 for (String name : map.keySet()) {
        if (!map.get(name).gameover) {
            for (int i = 0; i < map.get(name).length; i++) {
                rect = new Rectangle2D.Double(map.get(name).p[i].x,
                        map.get(name).p[i].y, width, width);
                g1.setColor(Color.black);
                g1.draw(rect);
                g1.setPaint(map.get(name).snakecolor);
                g1.fill(rect);
            }
        }
    }

The Hashmap map is a mapping from

        HashMap<String,Snake> 

where Snake is the class which has all the attributes of a snake. The main class also runs a thread side by side for receiving messages and updates from other clients through the server.

The iterator on the thread side also uses the same map(passed by reference to that class). Code for that is as given below. This function is called if the score of any player reaches some specific point after which the level is upgraded.

    void levelUp(int level){
    for(String name:map.keySet()){
        map.get(name).level=level;
    }
    Game.speed=100/level;
}

I think the clash between object write is due to this. Can anyone please suggest a solution for this problem.

The Code where I put values into the map is also given below.

void populateMap() {
    try {
        try {
            objin = new ObjectInputStream(socket.getInputStream());
        } catch (StreamCorruptedException e) {
            System.out.println("Stream Corrupted!");
        }
        Object name = objin.readObject();
        if (((Snake) name).player.equals("food_coord")) {
            Game.foodx = objin.readInt();
            Game.foody = objin.readInt() + 35;
            start = true;
            System.out.println("Game Started");
            return;
        } else {
            map.put(((Snake) name).player, (Snake) name);
            System.out.println("Recieved: " + ((Snake) name).player);
        }
    } catch (java.net.SocketException s) {
        JOptionPane.showMessageDialog(null, "Server Closed", "ERROR",
                JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

将地图实现类更改为支持并发的类,例如ConcurrentHashMap

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