Uses System.identityHashCode (Obj), reliably return unique identifier

I have a websocket implementation in the dropwizard service and they need to implement server side session management. When we connect, we get a session object, which is the glue between the client and the server. But they are not a way to get a unique ID for a session like session.getId () and I need an ID to manage the session.

So, I was thinking about using System.identityHashCode (Session) to get a unique ID and handle sessions using that ID.

for reference the websocket onConnect structure

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

      

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

+3


source to share


2 answers


identityHashMap is usually deduced from a memory address or random number generator tied to a stream and then stored in the object header when the JVM is first used. The probability of a collision is low, but not impossible.



Given the potential for collisions, why take the risk? mistakes that this can lead to being subtle and annoying to track down.

+3


source


WebSocketSession

- implementation Session

. It overrides hashCode

and equals

and can therefore be expected to safely hash 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);
    }

}

      

+1


source







All Articles