Quick tip: managing Stateful EJBs in WebSocket endpoints

@Stateful EJBs can be injected in WebSocket endpoints (supported by the WebSocket specification). There is an one-to-one association between the WebSocket client & endpoint (which is by default) as well as the injected Stateful EJB instance, which makes it an good candidate for storing client specific state. It offers advanced semantics as compared to simple java.util.Map interface exposed by getUserProperties method in javax.websocket.Session)

But, what happens to the EJB when ….

… the WebSocket session terminates (either from the client or server side) ?? The Stateful instance can still linger in memory before its destroyed

  • Their removal can be tuned by using the @StatefulTimeout annotation (but why wait ??), or
  • you can choose to passivate them by using passivationCapable=true with  @Stateful (but why passivate the EJB when the WebSocket connection itself is closed ?)

The Tip

Implement a @Remove annotated method in the Stateful EJB and call it from the @OnClose callback method ni your WebSocket server endpoint implementation. This will ensure that the  EJB is removed from the memory immediately rather than depending upon other factors

Further reading


About Abhishek

Loves Java EE, distributed KV stores and messaging systems. Frequently blogs at abhirockzz.wordpress.com as well as simplydistributed.wordpress.com. Oh, I have also authored a few (mini) books, articles, Refcards etc. :-)
This entry was posted in Java, Java EE and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s