Sets our connection reference in a thread safe way. Also establishes the back reference to
us as the connection's message handler.
358651
protected synchronized void setConnection (PresentsConnection conn)
    {
        long now = System.currentTimeMillis();
        if (_conn != null) {
            // if our connection is being cleared out, record the amount of time we were connected
            // to our total connected time
            if (conn == null) {
                _connectTime += ((now - _networkStamp) / 1000);
                _messagesDropped = 0;
            }

            // make damn sure we don't get any more messages from the old connection
            _conn.clearMessageHandler();
        }

        // keep a handle to the new connection
        _conn = conn;

        // if we're setting a connection rather than clearing one out...
        if (_conn != null) {
            // tell the connection to pass messages on to us
            _conn.setMessageHandler(this);

            // configure any active custom class loader
            if (_loader != null) {
                _conn.setClassLoader(_loader);
            }
        }

        // make a note that our network status changed
        _networkStamp = now;
    }
733171
public void onConnect() {
        input.setDisabled(false);
        sendingButton.setDisabled(false);
        connectingButton.setDisabled(true);
        disconnectingButton.setDisabled(false);
    }
1051911
private void restartPreviousConnection() throws CommunicationException, KeystoreException {
		try {
			logger.debug("Closing connection to restart previous one");
			this.socket.close();
		} catch (Exception e) {
			/* Do not complain if connection is already closed... */
		}
		initializePreviousConnection();
	}
1235712
public synchronized void start() {
        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mEngConnectedThread != null) {
            mEngConnectedThread.cancel();
            mEngConnectedThread = null;
        }
        if (mImpConnectedThread != null) {
            mImpConnectedThread.cancel();
            mImpConnectedThread = null;
        }

        setState(STATE_LISTEN);
    }
1103713
public static final void commit(final Connection connection) {
        if (connection == null) {
            return;
        }

        try {
            connection.commit();
        } catch (Exception e) {
            if (LOG.isWarnEnabled()) LOG.warn("Error committing Connection: " + connection, e);
        }
    }
824884
@Override
    protected void setCommsConnection(CommsConnection cc) {
        if (tc.isEntryEnabled())
            SibTr.entry(this, tc, "setCommsConnection");

        // Retrieve Client Conversation State if necessary
        validateConversationState();

        sConState.setCommsConnection(cc);

        if (tc.isEntryEnabled())
            SibTr.exit(this, tc, "setCommsConnection");
    }
24153
static WeakReference<Thread> currentThreadRef() {
        WeakReference<Thread> ref = weakThread.get();
        if (ref == null) {
            ref = new WeakReference<>(Thread.currentThread());
            weakThread.set(ref);
        }
        return ref;
    }
89259
public void addSICoreConnection(SICoreConnection conn, Conversation conversation) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "addSICoreConnection");

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            SibTr.debug(tc, "Params: connection, conversation",
                        new Object[] { conn, conversation });
        }

        conversationTable.put(conn, conversation);

        // At this point, if the me has previously been terminated, we know it is
        // back up - so make sure we remove if from our quiesce and terminated table
        // so that if it goes down again, we can notify the clients.
        quiesceNotif.remove(conn.getMeUuid());
        termNotif.remove(conn.getMeUuid());

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "addSICoreConnection");
    }
257162
protected void connectionErrorOccurred() {
        if (tc.isEntryEnabled()) {
            Tr.entry(this, tc, "connectionErrorOccurred");
        }
        connectionErrorOccurred(null);
        if (tc.isEntryEnabled()) {
            Tr.exit(this, tc, "connectionErrorOccurred");
        }
    }
999817
public static void setConnectionLocal(IConnection connection) {
        if (log.isDebugEnabled()) {
            log.debug("Set connection: {} with thread: {}", (connection != null ? connection.getSessionId() : null), Thread.currentThread().getName());
            try {
                StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
                StackTraceElement stackTraceElement = stackTraceElements[2];
                log.debug("Caller: {}.{} #{}", stackTraceElement.getClassName(), stackTraceElement.getMethodName(), stackTraceElement.getLineNumber());
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            connThreadLocal.set(new WeakReference<IConnection>(connection));
            IScope scope = connection.getScope();
            if (scope != null) {
                Thread.currentThread().setContextClassLoader(scope.getClassLoader());
            }
        } else {
            // use null to clear the value
            connThreadLocal.remove();
        }
    }
140185
def setConnection(self, connection):
        
        # define custom properties
        if not isinstance(connection, orb.Connection):
            conn = orb.Connection.byName(connection)
            if not conn:
                raise orb.errors.BackendNotFound(connection)
            connection = conn(self)
        else:
            connection.setDatabase(self)

        self.__connection = connection
942690
def _threadsafe_get_connection(self):
        """"""
        self._lock.acquire()
        try:
            next = self._nextConnection
            con = PooledDBConnection(self, self._connections[next])
            next += 1
            if next >= len(self._connections):
                next = 0
            self._nextConnection = next
            return con
        finally:
            self._lock.release()
956806
public void doReconnect() {
        if (channelRef.get() != null) {
            // if (channelRef.get().isWritable()) {
            // LOG.info("already exist a writable channel, give up reconnect, {}",
            // channelRef.get());
            // return;
            // }
            return;
        }

        if (isClosed()) {
            return;
        }

        if (isConnecting.getAndSet(true)) {
            LOG.info("Connect twice {}", name());
            return;
        }

        long sleepMs = getSleepTimeMs();
        LOG.info("Reconnect ... [{}], {}, sleep {}ms", retries.get(), name, sleepMs);
        ChannelFuture future = bootstrap.connect(remoteAddr);
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                isConnecting.set(false);
                Channel channel = future.getChannel();
                if (future.isSuccess()) {
                    // do something else
                    LOG.info("Connection established, channel = :{}", channel);
                    setChannel(channel);
                    // handleResponse();
                    BATCH_THRESHOLD_WARN = ConfigExtension.getNettyBufferThresholdSize(stormConf);

                    // Check if any pending message
                    /*synchronized (writeLock) {
                        if (channel != null && messageBuffer.size() > 0) {
                            MessageBatch messageBatch = messageBuffer.drain();
                            flushRequest(channel, messageBatch);
                        } else {
                            LOG.warn("Failed to flush pending message after reconnecting, channel={}, messageBuffer.size={}",
                                    channel, messageBuffer.size());
                        }
                    }*/
                } else {
                    if (!isClosed()) {
                        LOG.info("Failed to reconnect ... [{}], {}, channel = {}, cause = {}",
                                retries.get(), name, channel, future.getCause());
                        reconnect();
                    }
                }
            }
        });
        JStormUtils.sleepMs(sleepMs);
    }
641999
private void setStatus(ConnectionStatus status){
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("Set status to - " + status);
        }
        if(! this.status.equals(status)){
            ConnectionStatus pre = this.status;
            this.status = status;
            eventThread.queueClientEvent(new ClientStatusEvent(pre, status));
        }
    }
704609
protected synchronized void reset(Connection connection,
                        ReceiveListener listener,
                        WsByteBuffer data,
                        int size,
                        int segmentType,
                        int requestNumber,
                        int priority,
                        boolean allocatedFromPool,
                        boolean partOfExchange,
                        Conversation conversation)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "reset",
                                           new Object[]
                                           {
                                              connection,
                                              listener,
                                              data,
                                              ""+size,
                                              ""+segmentType,
                                              ""+requestNumber,
                                              ""+priority,
                                              ""+allocatedFromPool,
                                              ""+partOfExchange,
                                              conversation
                                           });

      this.connection = connection;
      this.listener = listener;
      this.data = data;
      this.size = size;
      this.segmentType = segmentType;
      this.requestNumber = requestNumber;
      this.priority = priority;
      this.allocatedFromPool = allocatedFromPool;
      this.partOfExchange = partOfExchange;
      this.conversation = conversation;
      setDispatchable(null);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "reset");
   }
1198306
protected void putConnectionBackInPartition(ThriftConnectionHandle<T> connectionHandle)
			throws ThriftConnectionPoolException {
		BlockingQueue<ThriftConnectionHandle<T>> queue = connectionHandle.getConnectionPartition().getFreeConnections();
		if (!queue.offer(connectionHandle)) { // 如果无法放回则关闭
			connectionHandle.internalClose();
		}
	}
253108
public static void setThreadInstance(Application application) {
		if (instance == null) {
			instance = new ThreadLocalApplication();
		} else if (!(instance instanceof ThreadLocalApplication)) {
			throw new IllegalStateException();
		}
		((ThreadLocalApplication) instance).setCurrentApplication(application);
	}