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

落爺英雄遲暮 提交于 2019-12-13 20:09:14

问题


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.


回答1:


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.




回答2:


  1. servers only hold references to the Server objects: whatever modification you make to the underlying objects will be reflected in servers too.
  2. Java passes references by value, so yes.

Note that if your code is not properly synchronized, you might see stale and/or inconsistent Server objects in your code, but that is a different issue.



来源:https://stackoverflow.com/questions/18492706/will-value-objects-in-a-copy-of-a-static-concurrenthashmap-reference-the-same-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!