By default …
… a WebSocket implementation creates a new (server) endpoint instance per client. In case you need a single instance, you can implement this using a custom
ServerEndpointConfig.Configurator (by overriding the
The catch: you might have to sacrifice some of the (Java EE) platform related services like dependency injection and interceptors
More details here
Alternate solution ?
A similar behavior can be achieved by decorating the WebSocket endpoint with
This approach has the caveat of not being a standard feature outlined by the spec (although injection of EJBs as well as interceptors support is clearly mentioned in the Java WebSocket spec Sec 7.1)
Concurrency semantics ?
In case of a
@Singleton, all the clients will interact with the one-and-only server endpoint instance. Here is a quick summary of how the EJB as well as WebSocket threading semantics are applied
Singletonbean default approach WRITE lock ensures single threaded access across all connected clients
- If thread-safety is not a concern (e.g. in case where you do not deal with client specific data/state in your logic) and in case the single-threaded access model proves to be a bottleneck, override the default behavior by switching to a READ lock which allows concurrent threads to access the methods (unless of course a WRITE lock is not already in effect)
Note: The above mentioned semantics are with respect to ALL the WebSocket clients. From the point of view of a single client, the default strategy of one thread at a time, per endpoint instance per client continues to apply (more details here)