private void stopConnectionMonitoring() {
   if (connectionMonitoringThread != null) {
     while (true) {
       try {
         connectionMonitoringThread.interrupt();
         connectionMonitoringThread.join();
         break;
       } catch (InterruptedException ex) {
         // ouch - let's try again!
       }
     }
   }
 }
  private void startConnectionMonitoring() {
    connectionMonitoringThread =
        new Thread() {
          @Override
          public void run() {
            LOGGER.debug("monitoring thread started");
            while (true) {
              try {
                // heart beat of 30s (should be configurable in the future)
                Thread.sleep(30000);

                // disconnect() was called.
                if (wantDisconnect) this.interrupt();

                if (lastPingSent != lastPingAck || websocketSession == null) {
                  // disconnection happened
                  LOGGER.warn("Connection lost...");
                  try {
                    if (websocketSession != null) {
                      websocketSession.close();
                    }
                  } catch (IOException e) {
                    LOGGER.error("exception while trying to close the websocket ", e);
                  }
                  websocketSession = null;
                  if (reconnectOnDisconnection) {
                    connectImpl();
                    continue;
                  } else {
                    this.interrupt();
                  }
                } else {
                  lastPingSent = getNextMessageId();
                  LOGGER.debug("sending ping " + lastPingSent);
                  try {
                    if (websocketSession.isOpen()) {
                      websocketSession
                          .getBasicRemote()
                          .sendText("{\"type\":\"ping\",\"id\":" + lastPingSent + "}");
                    } else if (reconnectOnDisconnection) {
                      connectImpl();
                    }
                  } catch (IllegalStateException e) {
                    // websocketSession might be closed in this case
                    if (reconnectOnDisconnection) {
                      connectImpl();
                    }
                  }
                }
              } catch (InterruptedException e) {
                break;
              } catch (IOException e) {
                LOGGER.error("unexpected exception on monitoring thread ", e);
              }
            }
            LOGGER.debug("monitoring thread stopped");
          }
        };

    if (!wantDisconnect) connectionMonitoringThread.start();
  }