静态 ConcurrentHashMap 副本中的值对象是否会引用与原始值对象相同的值对象? [英] Will value objects in a copy of a static ConcurrentHashMap reference the same value objects as the original?

查看:24
本文介绍了静态 ConcurrentHashMap 副本中的值对象是否会引用与原始值对象相同的值对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由两部分组成的问题.

I have a two part question.

我有:private static ConcurrentHashMap服务器= null;我后来填充.在方法 getAllServers 中,我这样做:

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;
}

问:对s的修改会反映在servers中吗?
问:toReturn 是否会引用与 servers 中相同的 Server 对象?如果是这样,任何创建和修改 getAllServers 返回的映射的类都会修改与 servers 相同的对象吗?

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?

更新:@chrylis:你指的是哪个 Iterator ?你能解释一下为什么 for 循环是一个坏主意吗?我在其他领域也使用它:

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();
                ...

但我没有发现任何问题,因为我知道 servers 将包含具有从 0 开始的 Integer id 的服务器.当我在 for 循环中迭代它们时,顺序不是我关心的问题.

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.

推荐答案

是的,是的.就这段代码而言,甚至不可能复制Server对象.这与 ConcurrentHashMap 无关,而与 Java 中引用的工作方式有关.

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.

这篇关于静态 ConcurrentHashMap 副本中的值对象是否会引用与原始值对象相同的值对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆