0

Recently, I'm learning about JEE7 websocket api, then I run a demo on newest Tomcat server, but I've found that the annotation @javax.inject.Singleton doesn't work, here's the demo code posted in Jiji_Sasidharan's blog: demo code

it work's well in glassfish4 server, but if run in Tomcat, ChatServerEndPoint instance won't be singleton, but an instance per client(peer), indicates that @Singleton doesn't work at all.

if I want to achieve the same result as it run on glassfish, I have to change the modifier of field : Set<Session> userSessions to : static Set<Session> userSessions.

in Chapter 6 session 1 of Tyrus(open source JSR 356) documentation

can anybody explain why, pls help, tks!

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Crystal Cat
  • 151
  • 1
  • 2
  • 10
  • How exactly did you install CDI in Tomcat? Tomcat doesn't ship with CDI out the box and therefore CDI needs to be installed manually in Tomcat. This problem indicates that you simply did it wrong. – BalusC Nov 19 '13 at 13:31
  • This answer may be helpful then: http://stackoverflow.com/a/19003725 – BalusC Nov 19 '13 at 13:32
  • thank you for helping me out! @BalusC – Crystal Cat Nov 19 '13 at 16:37

1 Answers1

2

@javax.inject.Singleton is part of CDI (Context and Dependency Injection).

And javax.websocket is part of the JSR-356 effort.

Interestingly, while the spec for javax.websocket (section 7.1.1) says that

Websocket implementations part of the Java EE platform are required to support field, method, and constructor injection using the javax.inject.Inject annotation into all websocket endpoint classes, as well as the use of interceptors for these classes.

The same spec does not mention support for other CDI features, such as @javax.inject.Singleton

The spec does however say (see Section 3.1.7) that for singleton Endpoints, you are to use a javax.websocket.server.ServerEndpointConfig.Configurator that overrides the .getEndpointInstance() and returns the same endpoint instance each time.

All non-tyrus implementations of javax.websocket support the spec, as-written. (see Jetty 9.1 and Tomcat)

Joakim Erdfelt
  • 41,193
  • 5
  • 78
  • 124
  • It's also worth pointing out that the websocket spec has many gaps when it comes to CDI. There is no definition of what scopes are active during the invocation of a websocket message. The scoping rules are the biggest issue, and you will find many incompatibilities along the way. – John Ament Nov 23 '13 at 03:48