5

I've read Java EE documentation and for me is unclear one thing. According to API, the only way to find another Session is a code like this: (assuming that we've identifier of other session):

import javax.websocket.Session;
...
private static Session findOtherSessionById(Session user, String id) {
    for (Session session : user.getOpenSessions()) {
        if (id.equals(session.getId())) {
            return session;
        }
    }
    return null;
}

But when we've thousands of users, this code is a performance bottleneck.

So, is there a way to get Session by id fast without using own ConcurrentHashMap for this? Or maybe some application server has undocummented feature for this (for me Wildfly would be great)?

omerhakanbilici
  • 874
  • 1
  • 18
  • 26
Ihromant
  • 163
  • 2
  • 8
  • did you find any solution? I'm using hazelcast.Imap and it can't store websocket.Session object. I need all Session objects for broadcast all sessions. – omerhakanbilici Nov 03 '16 at 11:29
  • Unfortunately not, currently I'm storing all Sessions in ConcurrentHashMap – Ihromant Dec 02 '16 at 16:53
  • our solution for clustered environments is using hazelcast topic to let know all clusters there is an event and they broadcast their stored sessions in map. – omerhakanbilici Dec 02 '16 at 21:21

1 Answers1

3

You can do something like:

Map<String, Session> map = new HashMap<>();
static Map<String, Session> peers = Collections.synchronizedMap(map);

@OnOpen
public void onOpen(Session session) {
   peers.put(session.getId(), session);
}

@OnClose
public void onClose(Session session) {
    peers.remove(session.getId());
}

private static Session findOtherSessionById(Session user, String id) {
    if (peers.containsKey(user.getId()) {
        return peers.get(user.getId());
    }
}
homerman
  • 3,369
  • 1
  • 16
  • 32
Arun Gupta
  • 3,965
  • 5
  • 31
  • 39
  • I have currently similar code with ConcurrentHashMap instead of synchronizedMap. I asked for another solution. Also when we have 2 application servers running, this code will fail. – Ihromant Nov 21 '14 at 18:06
  • 1
    @Ihromant for a distributed system you can use a distributed cache or information storage system, this may help http://stackoverflow.com/questions/27815056/distributed-hashmap-in-java-or-distributed-information-storage – Chen Oct 06 '15 at 16:26