Search code examples
javastaticsynchronizedconcurrenthashmap

Will value objects in a copy of a static ConcurrentHashMap reference the same value objects as the original?


I have a two part question.

I have: private static ConcurrentHashMap<Integer, Servers> servers= null; which I later populate. In method getAllServers, I'm doing this:

public static synchronized ConcurrentHashMap<Integer, Server> getAllServers() {
    ConcurrentHashMap<Integer, Server> toReturn = new ConcurrentHashMap<>();
    for(Integer i = 0; i < servers.size(); i ++ ) {
        Server s = servers.get(i);
        if(s.isAlive()) {
            s.incrementConns();
            toReturn.put(i, s);
        }
    }
    return toReturn;
}

Q: Will modifications to s be reflected in servers?
Q: Will toReturn reference the same Server objects as in servers? If so, would any class that creates and modifies getAllServers's returned map be modifiying the same objects as servers?

Update: @chrylis: Which Iterator are you referring to? Can you please explain why the for loop is a bad idea a bit more? I do use this as well, in other areas:

Iterator itr = servers.entrySet().iterator();
            Map.Entry pair;
            while(itr.hasNext()) {
                pair = (Map.Entry)itr.next();
                Server s= (Server) pair.getValue();
                ...

But I don't see anything wrong since I know servers will contain Servers with Integer ids ranging from 0 onward. When I iterate over them in the for loop, the order is not a concern for me.


Solution

  • Yes and yes. It may not even be possible to copy Server objects, as far as this code is concerned. This has nothing to do with ConcurrentHashMap, and everything to do with how references work in Java.