giannis christofakis
giannis christofakis

Reputation: 8321

Value removed from HashMap during iteration

I have a HashMap with the addresses and the names of the clients that are assigned on a server.When a user signs off everybody receives a message about his departure and then I remove him from the HashMap. The problem is when I iterate the HashMap in order to send to everyone the message I use a thread and as a result the users is removed before iteration happens, thus he don't receives the message. I tried Hashtable , ConcurrentHashMap in vain. When i skip the line of removal then it works. How can I avoid it ,can I use a different kind of map;

private HashMap<InetAddress, String> users = new HashMap<InetAddress, String>();

. . .

 UDPServerSender sender = new UDPServerSender(str, address, true);
                        sender.start();
                        users.remove(address);

. . .

public class UDPServerSender extends Thread {

    @Override
    public void run() {
            iterator = users.keySet().iterator();
            while (iterator.hasNext()) {
                InetAddress inetaddress = (InetAddress) iterator.next();

I figured I can send a separate message to the signed off users.

Upvotes: 2

Views: 211

Answers (1)

Diego
Diego

Reputation: 18359

Sounds like the thread should be removing the address, not the main thread. To do so, you will need to pass the HashMap to the thread.

Another alternative is to wait for the thread to finish before removing the address. Just use join to wait until the thread is done:

 UDPServerSender sender = new UDPServerSender(str, address, true);
                        sender.start();
                        sender.join();
                        users.remove(address);

Be aware that this second approach defeats the purpose of having a separate thread though, since it kills all parallelism (messages are now sent one by one).

Upvotes: 1

Related Questions