问题
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:
servers
only hold references to theServer
objects: whatever modification you make to the underlying objects will be reflected inservers
too.- 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