Is using System.identityHashCode(Obj) reliable to return unique Id

1.8k Views Asked by At

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.

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

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
}

So using System.identityHashCode(Session) will be good?

2

There are 2 best solutions below

4
On BEST ANSWER

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.

3
On

WebSocketSession is the implementation of Session. It overrides hashCode and equals and so can be expected to be hashed safely in programs using more than 4GB of memory. That is, the session is the key.

You can do something like this:

class YourClass 
{

    private Set<Session> managedSessions = new HashSet<Session>();
    // or use a Map<Session,Data> if you want to store associated data

    @OnWebSocketConnect
    public void onOpen(Session session) throws IOException
    {    
        if (managedSessions.contains(session)) {
            // working with preexisting session
        } else {
            managedSessions.add(session);
        }
    }

    @OnWebSocketClose
    public void onClose(Session session, int statusCode, String reason) 
    {
        managedSessions.remove(session);
    }

}