gpt4 book ai didi

java - 是否使用 System.identityHashCode(Obj) 可靠地返回唯一 ID

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:11:48 26 4
gpt4 key购买 nike

我在 dropwizard 服务中实现了 websocket,他们需要在服务器端实现 session 管理。在连接上,我们得到 session 对象,它是客户端和服务器之间的通信链接。但是他们不是像 session.getId() 这样的 session 获取唯一 ID 的方法,我需要 session 管理的 ID。

所以我一直在考虑使用 System.identityHashCode(Session) 来获取唯一 ID 并使用此 ID 处理 session 。

websocket onConnect结构仅供引用

@OnWebSocketConnect
public void onOpen(Session session) throws IOException
{
// code to add the session in session management using unique id
}

那么使用 System.identityHashCode(Session) 会好吗?

最佳答案

identityHashMap 通常派生自内存地址或绑定(bind)到线程的随机数生成器,然后在 JVM 首次使用时存储在对象 header 中。发生碰撞的可能性很低,但并非不可能。

鉴于可能会发生碰撞,为什么要冒险呢?这可能导致的错误将是微妙的并且难以追踪。

关于java - 是否使用 System.identityHashCode(Obj) 可靠地返回唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26910094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com