if either of these happen, the user will need to renegotiate a connection via reopen
433623
def assert_open
    @mutex.synchronize do
      raise Exceptions::NotConnected if !@czk or @czk.closed?
      if forked?
        raise InheritedConnectionError, <<-EOS.gsub(/(?:^|\n)\s*/, ' ').strip
          You tried to use a connection inherited from another process 
          (original pid: #{original_pid}, your pid: #{Process.pid})
          You need to call reopen() after forking
        EOS
      end
    end
  end
1332560
public void reconnect(boolean callFromQueue) throws InterruptedException
    {
        Set<MDC.MDCCloseable> contextEntries = null;
        Map<String, String> previousContext = null;
        {
            ConcurrentMap<String, String> contextMap = api.getContextMap();
            if (callFromQueue && contextMap != null)
            {
                previousContext = MDC.getCopyOfContextMap();
                contextEntries = contextMap.entrySet().stream()
                          .map((entry) -> MDC.putCloseable(entry.getKey(), entry.getValue()))
                          .collect(Collectors.toSet());
            }
        }
        if (shutdown)
        {
            api.setStatus(JDA.Status.SHUTDOWN);
            api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
            return;
        }
        String message = "";
        if (callFromQueue)
            message = String.format("Queue is attempting to reconnect a shard...%s ", shardInfo != null ? " Shard: " + shardInfo.getShardString() : "");
        LOG.debug("{}Attempting to reconnect in {}s", message, reconnectTimeoutS);
        while (shouldReconnect)
        {
            api.setStatus(JDA.Status.WAITING_TO_RECONNECT);
            int delay = reconnectTimeoutS;
            Thread.sleep(delay * 1000);
            handleIdentifyRateLimit = false;
            api.setStatus(JDA.Status.ATTEMPTING_TO_RECONNECT);
            LOG.debug("Attempting to reconnect!");
            try
            {
                connect();
                break;
            }
            catch (RejectedExecutionException ex)
            {
                // JDA has already been shutdown so we can stop here
                api.setStatus(JDA.Status.SHUTDOWN);
                api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
                return;
            }
            catch (RuntimeException ex)
            {
                reconnectTimeoutS = Math.min(reconnectTimeoutS << 1, api.getMaxReconnectDelay());
                LOG.warn("Reconnect failed! Next attempt in {}s", reconnectTimeoutS);
            }
        }
        if (contextEntries != null)
            contextEntries.forEach(MDC.MDCCloseable::close);
        if (previousContext != null)
            previousContext.forEach(MDC::put);
    }
1226041
def reconnect(self):
        
        self.connect(*self._saved_connect.args, **self._saved_connect.kwargs)
936967
def reconnect(self):
        
        connect_attempt = 0
        max_retries = self.config['max_reconnect_retries']
        logging.info('attempting to reconnect to crossbar')
        runner = self.setup_runner()
        while True:

            if connect_attempt == max_retries:
                logging.info('max retries reached; stopping service')
                sys.exit(1)
            self.check_event_loop()

            try:
                logging.info('waiting 5 seconds')
                time.sleep(5)
                if self.check_transport_host():
                    logging.info('waiting 10 seconds to ensure that crossbar has initialized before reconnecting')
                    time.sleep(10)
                    runner.run(Component)
                else:
                    logging.error('crossbar host port 8080 not available...')
            except RuntimeError as error:
                logging.error(error)
            except ConnectionRefusedError as error:
                logging.error(error)
            except ConnectionError as error:
                logging.error(error)
            except KeyboardInterrupt:
                logging.info('User initiated shutdown')
                loop = asyncio.get_event_loop()
                loop.stop()
                sys.exit(1)
            connect_attempt += 1
232546
def reconnect(url=nil, user=nil, pass=nil, opts={})
    @connection_pool.disconnect!
    connect(url, user, pass, opts)
  end
332023
function(sourceWasAnError, shouldNotReconnect) {
      log.error("[Endpoint] Connection closed " + (sourceWasAnError ? 'because of an error:' + sourceWasAnError : ''));

      this.connected = false;
      this.handshaken = false;
      this.connecting = false;

      if (!shouldNotReconnect) {
        log.debug('onClose():: reconnecting...');
        this.handshakenBackoff.reset();
        this.reconnectBackoff.backoff();
      } else {
        log.debug('onClose():: don\'t reconnect');
        this.handshakenBackoff.reset();
        this.reconnectBackoff.reset();
      }

      this.emit('close', sourceWasAnError);
    }
1136085
private void performReconnect() {
        if (null != applicationID) {
            reconnectCount++;

            new java.util.Timer().schedule(
                new java.util.TimerTask() {
                    @Override
                    public void run() {
                        actuallyReconnect();
                    }
                },
                RECONNECT_INTERVAL * (reconnectCount - 1)
            );
        }
    }
35710
def reconnect(self):
        """"""
        if len(self._host) == 0:
            raise ValueError('Invalid host.')
        if self._port <= 0:
            raise ValueError('Invalid port number.')

        self._in_packet = {
            "command": 0,
            "have_remaining": 0,
            "remaining_count": [],
            "remaining_mult": 1,
            "remaining_length": 0,
            "packet": b"",
            "to_process": 0,
            "pos": 0}

        self._out_packet_mutex.acquire()
        self._out_packet = []
        self._out_packet_mutex.release()

        self._current_out_packet_mutex.acquire()
        self._current_out_packet = None
        self._current_out_packet_mutex.release()

        self._msgtime_mutex.acquire()
        self._last_msg_in = time.time()
        self._last_msg_out = time.time()
        self._msgtime_mutex.release()

        self._ping_t = 0
        self._state_mutex.acquire()
        self._state = mqtt_cs_new
        self._state_mutex.release()
        if self._ssl:
            self._ssl.close()
            self._ssl = None
            self._sock = None
        elif self._sock:
            self._sock.close()
            self._sock = None

        # Put messages in progress in a valid state.
        self._messages_reconnect_reset()

        try:
            if (sys.version_info[0] == 2 and sys.version_info[1] < 7) or (sys.version_info[0] == 3 and sys.version_info[1] < 2):
                sock = socket.create_connection((self._host, self._port))
            else:
                sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
        except socket.error as err:
            if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
                raise

        verify_hostname = self._tls_insecure is False  # Decide whether we need to verify hostname

        if self._tls_ca_certs is not None:
            if self._useSecuredWebsocket:
                # Never assign to ._ssl before wss handshake is finished
                # Non-None value for ._ssl will allow ops before wss-MQTT connection is established
                rawSSL = ssl.wrap_socket(sock, ca_certs=self._tls_ca_certs, cert_reqs=ssl.CERT_REQUIRED)  # Add server certificate verification
                rawSSL.setblocking(0)  # Non-blocking socket
                self._ssl = SecuredWebSocketCore(rawSSL, self._host, self._port, self._AWSAccessKeyIDCustomConfig, self._AWSSecretAccessKeyCustomConfig, self._AWSSessionTokenCustomConfig)  # Override the _ssl socket
                # self._ssl.enableDebug()
            elif self._alpn_protocols is not None:
                # SSLContext is required to enable ALPN support
                # Assuming Python 2.7.10+/3.5+ till the end of this elif branch
                ssl_context = SSLContextBuilder()\
                    .with_ca_certs(self._tls_ca_certs)\
                    .with_cert_key_pair(self._tls_certfile, self._tls_keyfile)\
                    .with_cert_reqs(self._tls_cert_reqs)\
                    .with_check_hostname(True)\
                    .with_ciphers(self._tls_ciphers)\
                    .with_alpn_protocols(self._alpn_protocols)\
                    .build()
                self._ssl = ssl_context.wrap_socket(sock, server_hostname=self._host, do_handshake_on_connect=False)
                verify_hostname = False  # Since check_hostname in SSLContext is already set to True, no need to verify it again
                self._ssl.do_handshake()
            else:
                self._ssl = ssl.wrap_socket(
                    sock,
                    certfile=self._tls_certfile,
                    keyfile=self._tls_keyfile,
                    ca_certs=self._tls_ca_certs,
                    cert_reqs=self._tls_cert_reqs,
                    ssl_version=self._tls_version,
                    ciphers=self._tls_ciphers)

            if verify_hostname:
                if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 5):  # No IP host match before 3.5.x
                    self._tls_match_hostname()
                else:
                    ssl.match_hostname(self._ssl.getpeercert(), self._host)

        self._sock = sock

        if self._ssl and not self._useSecuredWebsocket:
            self._ssl.setblocking(0)  # For X.509 cert mutual auth.
        elif not self._ssl:
            self._sock.setblocking(0)  # For plain socket
        else:
            pass  # For MQTT over WebSocket

        return self._send_connect(self._keepalive, self._clean_session)
1006100
@Override
	public synchronized boolean reconnect() {
		logger.debug("reconnect() called");
		try {
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_INIT);
			websocketEndpoint.close();

			permissions = BitfinexApiKeyPermissions.NO_PERMISSIONS;
			authenticated = false;
			sequenceNumberAuditor.reset();
			connectionFeatureManager.setActiveConnectionFeatures(0);

			// Invalidate old data
			quoteManager.invalidateTickerHeartbeat();
			orderManager.clear();
			positionManager.clear();

			final CountDownLatch connectionReadyLatch = new CountDownLatch(4);

			final Closeable authSuccessEventCallback = callbackRegistry.onAuthenticationSuccessEvent(c -> {
				permissions = c.getPermissions();
				authenticated = true;
				connectionReadyLatch.countDown();
			});
			final Closeable authFailedCallback = callbackRegistry.onAuthenticationFailedEvent(c -> {
				permissions = c.getPermissions();
				authenticated = false;
				while (connectionReadyLatch.getCount() != 0) {
					connectionReadyLatch.countDown();
				}
			});
			
			final Closeable positionInitCallback = callbackRegistry.onMyPositionEvent((a, p) -> connectionReadyLatch.countDown());
			final Closeable walletsInitCallback = callbackRegistry.onMyWalletEvent((a, w) -> connectionReadyLatch.countDown());
			final Closeable orderInitCallback = callbackRegistry.onMySubmittedOrderEvent((a, o) -> connectionReadyLatch.countDown());

			// Reset account info handler
			setupDefaultAccountInfoHandler();

			websocketEndpoint.connect();

			connectionFeatureManager.applyConnectionFeatures();
			if( configuration.isAuthenticationEnabled()) {
				authenticateAndWait(connectionReadyLatch);
			}
			authSuccessEventCallback.close();
			authFailedCallback.close();
			positionInitCallback.close();
			walletsInitCallback.close();
			orderInitCallback.close();

			resubscribeChannels();

			updateConnectionHeartbeat();
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_SUCCESS);
			return true;
		} catch (final Exception e) {
			logger.error("Got exception while reconnect", e);
			websocketEndpoint.close();
			callbackRegistry.acceptConnectionStateChange(BitfinexConnectionStateEnum.RECONNECTION_FAILED);
			return false;
		}
	}
904299
def _reconnect_cb(self):
        """"""
        @asyncio.coroutine
        def try_reconnect():
            """Actual coroutine ro try to reconnect or reschedule."""
            try:
                yield from self._do_connect()
            except IOError:
                self._loop.call_later(SERVER_RECONNECT_DELAY,
                                      self._reconnect_cb)
        asyncio.ensure_future(try_reconnect())
249815
synchronized boolean doReConnect() throws IOException {

        // In case we are still connected, test the connection and see if we can reuse it
        if(connectionManager.isConnected()) {
            try {
                final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();
                result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much
                return true;
            } catch (Exception e) {
                ServerLogger.AS_ROOT_LOGGER.debugf(e, "failed to ping the host-controller, going to reconnect");
            }
            // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect
            final Connection connection = connectionManager.getConnection();
            StreamUtils.safeClose(connection);
            if(connection != null) {
                try {
                    // Wait for the connection to be closed
                    connection.awaitClosed();
                } catch (InterruptedException e) {
                    throw new InterruptedIOException();
                }
            }
        }

        boolean ok = false;
        final Connection connection = connectionManager.connect();
        try {
            // Reconnect to the host-controller
            final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);
            try {
                boolean inSync = result.getResult().get();
                ok = true;
                reconnectRunner = null;
                return inSync;
            } catch (ExecutionException e) {
                throw new IOException(e);
            } catch (InterruptedException e) {
                throw new InterruptedIOException();
            }
        } finally {
            if(!ok) {
                StreamUtils.safeClose(connection);
            }
        }
    }
419029
private void executeReconnect() throws InterruptedException {
		// Close connection
		websocketEndpoint.close();

		// Store the reconnect time to prevent to much
		// reconnects in a short timeframe. Otherwise the
		// rate limit will apply and the reconnects are not successfully
		logger.info("Wait for next reconnect timeslot");
		eventsInTimeslotManager.recordNewEvent();
		eventsInTimeslotManager.waitForNewTimeslot();
		logger.info("Wait for next reconnect timeslot DONE");

		bitfinexApiBroker.reconnect();
	}
1256436
def release(self, conn):
        """"""
        if conn.in_transaction:
            raise InvalidRequestError(
                "Cannot release a connection with "
                "not finished transaction"
            )
        raw = conn.connection
        res = yield from self._pool.release(raw)
        return res
404581
boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {
        // Disconnect the remote connection.
        // WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't
        // be informed that the channel has closed
        protocolClient.disconnected(old);

        synchronized (this) {
            // If the connection dropped without us stopping the process ask for reconnection
            if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {
                final InternalState state = internalState;
                if (state == InternalState.PROCESS_STOPPED
                        || state == InternalState.PROCESS_STOPPING
                        || state == InternalState.STOPPED) {
                    // In case it stopped we don't reconnect
                    return true;
                }
                // In case we are reloading, it will reconnect automatically
                if (state == InternalState.RELOADING) {
                    return true;
                }
                try {
                    ROOT_LOGGER.logf(DEBUG_LEVEL, "trying to reconnect to %s current-state (%s) required-state (%s)", serverName, state, requiredState);
                    internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);
                } catch (Exception e) {
                    ROOT_LOGGER.logf(DEBUG_LEVEL, e, "failed to send reconnect task");
                }
                return false;
            } else {
                return true;
            }
        }
    }
58781
private void reconnectAfter(final long timeInMillis) {
    new Thread() {
      @Override
      public void run() {
        LOGGER.info("Schedule reconnect after {} millis", timeInMillis);
        try {
          Thread.sleep(timeInMillis);
        }
        catch (InterruptedException e) {
        }

        int attempt = 0;
        while (session == null || session.getSessionState().equals(SessionState.CLOSED)) {
          try {
            LOGGER.info("Reconnecting attempt #{} ...", ++attempt);
            session = newSession();
          }
          catch (IOException e) {
            LOGGER.error("Failed opening connection and bind to " + remoteIpAddress + ":" + remotePort, e);
            // wait for a second
            try {
              Thread.sleep(1000);
            }
            catch (InterruptedException ee) {
            }
          }
        }
      }
    }.start();
  }
866710
void dropConnection(SibRaMessagingEngineConnection connection, boolean isSessionError, boolean retryImmediately, boolean alreadyClosed)
    {
        String methodName = "dropConnection";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.entry(this, TRACE, methodName,
                        new Object[] { connection, Boolean.valueOf(isSessionError), Boolean.valueOf(retryImmediately), Boolean.valueOf(alreadyClosed) });
        }

        SibRaMessagingEngineConnection connectionCheck = null;
        String meUuid = connection.getConnection().getMeUuid();

        synchronized (_connections)
        {
            /*
             * Does the connection that we've been passed, still exist?
             */
            connectionCheck = _connections.get(meUuid);

            /*
             * If the connection object that we've been passed is the same object as that retrieved from _connections, close it.
             */
            if (connection == connectionCheck)
            {
                closeConnection(meUuid, alreadyClosed);
            }
        }

        // If we are reloading the engine then don't try and reconnect now. Wait until we get an engine 
        // reloaded shoulder tap. Since we don't know if remote MEs are having an engine reloaded we will fail 
        // the connection and deactivate the MDB. The connection is only passed in as a parameter from session
        // error method call.
        if (!isSessionError ||
            (!SibRaEngineComponent.isMessagingEngineReloading(meUuid)))
        {
            // PM49608 The lock hierarchy is first _timerLock and then _connections
            // This hierarchy is necessary to avoid deadlock
            synchronized (_timerLock)
            {
                synchronized (_connections)
                {
                    // If this was our last (or only) connection then kick off another loop to check if
                    // we can obtain a new connection.
                    if (_connections.size() == 0)
                    {
                        try
                        {
                            clearTimer();
                            if (retryImmediately)
                            {
                                timerLoop();
                            }
                            else
                            {
                                kickOffTimer();
                            }
                        } catch (final ResourceException resEx)
                        {
                            FFDCFilter.processException(resEx, CLASS_NAME + "."
                                                               + methodName, "1:1434:1.45", this);

                            SibTr.error(TRACE, "CONNECT_FAILED_CWSIV0783", new Object[] {
                                                                                         _endpointConfiguration.getDestination()
                                                                                                         .getDestinationName(),
                                                                                         _endpointConfiguration.getBusName(), this, resEx });
                        }
                    }
                }
            }
        }
        else
        {
            // Stop any timers as no point in trying again until we have finished reloading the engine.
            clearTimer();
        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.exit(this, TRACE, methodName);
        }
    }
661423
public void reconnect() throws SQLException {
    boolean inTransaction = currentProtocol != null && currentProtocol.inTransaction();
    reconnectFailedConnection(new SearchFilter(true, false));
    handleFailLoop();
    if (inTransaction) {
      throw new ReconnectDuringTransactionException(
          "Connection reconnect automatically during an active transaction", 1401, "25S03");
    }
  }