title: Java/Tomcat: how to handle WebSocket setup completion
body: <p>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.</p>
  
  <p>How can I handle the most correctly, that internal WebSockets mechanism is up and I can start using WebSockets?</p>
  
  <p>Application is based on Spring 4.</p>
  
  <p>I tried this <a href="https://stackoverflow.com/questions/2401489/execute-method-on-startup-in-spring">Execute method on startup in spring</a>, this <a href="https://stackoverflow.com/questions/8686507/how-to-add-a-hook-to-the-application-context-initialization-event">How to add a hook to the application context initialization event?</a> and this <a href="https://stackoverflow.com/questions/4747525/tomcat-after-startup-event-with-spring">Tomcat after Startup Event with spring</a> . </p>
  
  <p>All this approaches are cool but seems that on that moments WebSockets are still not ready to be used. 
  Next exception is thrown:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>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.</p>
  
  <p>Any ideas? Thanks!</p>