是否使用 System.identityHashCode(Obj) 可靠返回唯一 Id [英] Is using System.identityHashCode(Obj) reliable to return unique Id

查看:75
本文介绍了是否使用 System.identityHashCode(Obj) 可靠返回唯一 Id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a implementation of websocket in dropwizard service and theirs a need to implement session management on server side. On connection we get session object which is the communication link between client and server. But their is not way to get Unique id for session like session.getId() and i need id for session management.

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

So i have been thinking of using System.identityHashCode(Session) to get unique id and handle sessions using this ID.

仅供参考,websocket onConnect 结构是

just for reference the websocket onConnect structure is

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

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

推荐答案

identityHashMap 通常从内存地址或绑定到线程的随机数生成器派生,然后在 JVM 首次使用时存储在对象头中.碰撞的可能性很小,但并非不可能.

identityHashMap is usually derived from a memory address or a random number generator tied to a thread and then stored within the object header on first use by the JVM. The likelihood of collision is low, but not impossible.

既然会发生碰撞,为什么要冒险呢?这可能导致的错误很微妙,并且很难追踪.

Given that collisions can occur, why risk it? the bugs that this could lead to would be subtle and irritating to track down.

这篇关于是否使用 System.identityHashCode(Obj) 可靠返回唯一 Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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