javaspringtomcatwebsocketjsr356

Java/Tomcat: how to handle WebSocket setup completion


I have the following scenario: few Tomcat instances with the same application need to connect between each other on startup. For connection between servers, WebSockets (JSR-356) are used. When Tomcat has started, I need to initiate the establishment with another server.

How can I handle the most correctly, that internal WebSockets mechanism is up and I can start using WebSockets?

Application is based on Spring 4.

I tried this Execute method on startup in spring, this How to add a hook to the application context initialization event? and this Tomcat after Startup Event with spring .

All this approaches are cool but seems that on that moments WebSockets are still not ready to be used. Next exception is thrown:

javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed    
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:373)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:201)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:222)
...
Caused by: java.util.concurrent.TimeoutException
at sun.nio.ch.PendingFuture.get(PendingFuture.java:197)
at org.apache.tomcat.websocket.WsWebSocketContainer.processResponse(WsWebSocketContainer.java:599)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:343)

For now, as a workaround, I use 3 seconds delays in WebServlet's init() method before establishing the connection but it is kinda hack I would like to avoid.

Any ideas? Thanks!


Solution

  • I have solved it just by setting connection establishment into separate thread. Without separate thread, it blocks the continue of Tomcat startup. Hope it will help one day to somebody.