private void doClose(final boolean sendClose) {
    if (state == STATE.CLOSED) {
      if (HornetQLogger.LOGGER.isDebugEnabled()) {
        HornetQLogger.LOGGER.debug(this + " is already closed when calling closed");
      }
      return;
    }

    state = STATE.CLOSING;

    if (discoveryGroup != null) {
      synchronized (this) {
        try {
          discoveryGroup.stop();
        } catch (Exception e) {
          HornetQLogger.LOGGER.failedToStopDiscovery(e);
        }
      }
    } else {
      staticConnector.disconnect();
    }

    synchronized (connectingFactories) {
      for (ClientSessionFactoryInternal csf : connectingFactories) {
        csf.close();
      }
      connectingFactories.clear();
    }

    Set<ClientSessionFactoryInternal> clonedFactory;
    synchronized (factories) {
      clonedFactory = new HashSet<ClientSessionFactoryInternal>(factories);

      factories.clear();
    }

    for (ClientSessionFactory factory : clonedFactory) {
      if (sendClose) {
        factory.close();
      } else {
        factory.cleanup();
      }
    }

    if (shutdownPool) {
      if (threadPool != null) {
        threadPool.shutdown();

        try {
          if (!threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS)) {
            HornetQLogger.LOGGER.timedOutWaitingForTermination();
          }
        } catch (InterruptedException ignore) {
        }
      }

      if (scheduledThreadPool != null) {
        scheduledThreadPool.shutdown();

        try {
          if (!scheduledThreadPool.awaitTermination(10000, TimeUnit.MILLISECONDS)) {
            HornetQLogger.LOGGER.timedOutWaitingForScheduledPoolTermination();
          }
        } catch (InterruptedException ignore) {
        }
      }
    }
    readOnly = false;

    state = STATE.CLOSED;
  }