在范围里随机找一个空闲端口,from Spring SocketUtils.

@throws IllegalStateException 最多尝试(maxPort-minPort)次，如无空闲端口，抛出此异常.
438240
public static int findRandomAvailablePort(int minPort, int maxPort) {
		int portRange = maxPort - minPort;
		int candidatePort;
		int searchCounter = 0;

		do {
			if (++searchCounter > portRange) {
				throw new IllegalStateException(
						String.format("Could not find an available tcp port in the range [%d, %d] after %d attempts",
								minPort, maxPort, searchCounter));
			}
			candidatePort = minPort + random.nextInt(portRange + 1);
		} while (!isPortAvailable(candidatePort));

		return candidatePort;
	}
144396
public T get() throws IllegalStateException {
    switch (this.state) {
      case INCOMPLETE:
        // Do not block browser so just throw ex
        throw new IllegalStateException("The server response did not yet recieved.");
      case FAILED:
        throw new IllegalStateException(this.error);
      case SUCCEEDED:
        return this.value;
      default:
        throw new IllegalStateException("Something very unclear");
    }
  }
1298177
protected HttpServletRequest getCurrentRequest() {
        final HttpServletRequest request = httpService.getCurrentRequest();
        if (request == null) {
            throw new IllegalStateException("No HttpServletRequest bound to current thread");
        }
        return request;
    }
1327668
synchronized int getNextFreePort() {

		while (true) {

			// Acquire a control port
			while (myCurrentControlSocketPort == null) {
				int nextCandidate = (int) (Math.random() * 65000.0);
				nextCandidate = nextCandidate - (nextCandidate % SPACE_SIZE);

				if (nextCandidate < 10000) {
					continue;
				}

				try {
					ServerSocket server = new ServerSocket();
					server.setReuseAddress(true);
					server.bind(new InetSocketAddress("localhost", nextCandidate));
					myControlSockets.add(server);
					ourLog.info("Acquired control socket on port {}", nextCandidate);
					myCurrentControlSocketPort = nextCandidate;
					myCurrentOffset = 0;
				} catch (IOException theE) {
					ourLog.info("Candidate control socket {} is already taken", nextCandidate);
					continue;
				}
			}

			// Find a free port within the allowable range
			while (true) {
				myCurrentOffset++;

				if (myCurrentOffset == SPACE_SIZE) {
					// Current space is exhausted
					myCurrentControlSocketPort = null;
					break;
				}

				int nextCandidatePort = myCurrentControlSocketPort + myCurrentOffset;

				// Try to open a port on this socket and use it
				if (!isAvailable(nextCandidatePort)) {
					continue;
				}

				// Log who asked for the port, just in case that's useful
				StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
				StackTraceElement previousElement = Arrays.stream(stackTraceElements)
					.filter(t -> !t.toString().contains("PortUtil.") && !t.toString().contains("getStackTrace"))
					.findFirst()
					.orElse(stackTraceElements[2]);
				ourLog.info("Returned available port {} for: {}", nextCandidatePort, previousElement.toString());

				try {
					Thread.sleep(ourPortDelay);
				} catch (InterruptedException theE) {
					// ignore
				}

				return nextCandidatePort;

			}


		}
	}
1360841
PollingState<T> withStatus(String status, int statusCode) throws IllegalArgumentException {
        if (status == null) {
            throw new IllegalArgumentException("Status is null.");
        }
        this.status = status;
        this.statusCode = statusCode;
        return this;
    }
99552
public int getPort() {
    if (port != null && port != 0) {
      return port;
    }
    return urlParser != null ? urlParser.getHostAddresses().get(0).port : 3306;
  }
785802
private TProtocol createTProtocol(TTransport transport) {
		if (tProtocolType == TProtocolType.BINARY) {
			return new TBinaryProtocol(transport);
		} else if (tProtocolType == TProtocolType.JSON) {
			return new TJSONProtocol(transport);
		}
		throw new IllegalStateException("暂不支持的管道类型：" + tProtocolType);
	}
84744
@Override
	public synchronized ThriftSocket buildThriftSocket(ClientSocketPoolParameters parameters) throws IkasoaException {
		if (!ServerUtil.checkHostAndPort(parameters.getHost(), parameters.getPort()))
			throw new IllegalArgumentException("Server host or port is null !");
		SimpleSocketPoolImpl self = selfMap.get(parameters.getKey());
		if (self == null || self.socketStatusArray == null)
			self = init(parameters);
		byte i = 0;
		for (; i < size; i++)
			if (!self.socketStatusArray[i]) {
				ThriftSocket thriftSocket = getThriftSocket(self, i, parameters);
				if (!thriftSocket.isOpen()) {
					// 如果socket未连接,则新建一个socket
					// TODO: 用isOpen方法判断是否保持连接并不准确,所以这里有可能会额外创建一些socket
					thriftSocket = parameters.buildClientThriftSocket();
					self.socketPool.put(new Byte(i), thriftSocket);
				}
				self.socketStatusArray[i] = Boolean.TRUE;
				return thriftSocket;
			}
		// 如果连接不够用,就初始化连接池.
		try {
			for (i = 0; i < size; i++) {
				ThriftSocket thriftSocket = self.socketPool.get(i);
				if (self.socketStatusArray[i] && (thriftSocket == null || thriftSocket.getSocket() == null
						|| (thriftSocket.isOpen() && thriftSocket.getSocket().isClosed()))) {
					return parameters.buildClientThriftSocket();
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		log.warn("Not enough pooled connection ! Again retry initiation pool .");
		init(parameters);
		return buildThriftSocket(parameters);
	}
511989
@Override
    public int getUOWTimeout() throws IllegalStateException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getUOWTimeout", this);

        final int timeout;
        final int uowType = getUOWType();

        switch (uowType) {
            case UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION:
                try {
                    timeout = ((EmbeddableTransactionImpl) getUOWScope()).getTimeout();
                } catch (SystemException e) {
                    final IllegalStateException ise = new IllegalStateException(e);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                        Tr.exit(tc, "getUOWTimeout", ise);
                    throw ise;
                }
                break;

            default:
                final IllegalStateException ise = new IllegalStateException("Invalid UOW type: " + uowType);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    Tr.exit(tc, "getUOWTimeout", ise);
                throw ise;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getUOWTimeout", new Integer(timeout));
        return timeout;
    }
1310292
public static TreeSet<Integer> getUsableLocalPorts(int numRequested, int minPort, int maxPort) {
		final TreeSet<Integer> availablePorts = new TreeSet<>();
		int attemptCount = 0;
		while ((++attemptCount <= numRequested + 100) && availablePorts.size() < numRequested) {
			availablePorts.add(getUsableLocalPort(minPort, maxPort));
		}

		if (availablePorts.size() != numRequested) {
			throw new UtilException("Could not find {} available  ports in the range [{}, {}]", numRequested, minPort, maxPort);
		}

		return availablePorts;
	}
286212
public OutputStream getRequestOutputStream()
        throws IOException, IllegalStateException {
        LOG.trace("enter HttpConnection.getRequestOutputStream()");
        assertOpen();
        OutputStream out = this.outputStream;
        if (Wire.CONTENT_WIRE.enabled()) {
            out = new WireLogOutputStream(out, Wire.CONTENT_WIRE);
        }
        return out;
    }
159933
@Override
    public VirtualConnectionFactory getOutboundVCFactory(Map<Object, Object> sslProps, boolean overwriteExisting) throws IllegalStateException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "getOutboundVCFactory(ssl)");
        }

        // Ensure the SSL channel factory exists in the outbound channel
        // definitions.
        if (-1 == this.sslChannelIndex) {
            throw new IllegalStateException("The SSL channel factory does not exist in this CFEndPoint.");
        }

        // Create a new OutboundChannelDefintion with new properties.
        OutboundChannelDefinition existingDef = this.outboundChannelDefs.get(this.sslChannelIndex);
        OutboundChannelDefinition newChannelDef = new OutboundChannelDefinitionImpl(existingDef, sslProps, overwriteExisting);
        // Overlay the new definition into the array managed by this endpoint.
        this.outboundChannelDefs.add(this.sslChannelIndex, newChannelDef);
        // Now that the properties are folded in, call the basic implementation.
        VirtualConnectionFactory localVCF = getOutboundVCFactory();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "getOutboundVCFactory(ssl)");
        }
        return localVCF;
    }
772540
@Nullable
  ClientTransport obtainActiveTransport() {
    ClientTransport savedTransport = activeTransport;
    if (savedTransport != null) {
      return savedTransport;
    }
    try {
      synchronized (lock) {
        savedTransport = activeTransport;
        // Check again, since it could have changed before acquiring the lock
        if (savedTransport != null) {
          return savedTransport;
        }
        if (state.getState() == IDLE) {
          channelLogger.log(ChannelLogLevel.INFO, "CONNECTING as requested");
          gotoNonErrorState(CONNECTING);
          startNewTransport();
        }
      }
    } finally {
      syncContext.drain();
    }
    return null;
  }
866808
@Override
    public java.net.Socket createSocket() throws IOException {
        // This is the code to support outbound ssl config for an unconnected socket.
        // To make this code work, the caller side needs to set either sslProperties by using setSSLPropertiesOnThread
        // or outbound connection info with host/port information by using setOutboundConnectionInfo.
        // Either case, the thread attached information needs to be cleared after creating a socket.
        if (tc.isEntryEnabled())
            Tr.entry(tc, "createSocket");
        javax.net.ssl.SSLSocketFactory currentFactory = default_factory;
        javax.net.ssl.SSLSocket socket = null;
        java.util.Properties sslProps = props;
        if (default_constructor) {
            try {
                java.util.Properties sslPropsOnThread = getSSLPropertiesOnThread();
                java.util.Map<String, Object> currentConnectionInfo = JSSEHelper.getInstance().getOutboundConnectionInfo();
                if ((sslPropsOnThread != null) || (currentConnectionInfo != null)) {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "either SSLProperties on thread or connectionInfo is available.");
                    if (currentConnectionInfo == null) {
                        currentConnectionInfo = new HashMap<String, Object>();
                        currentConnectionInfo.put(Constants.CONNECTION_INFO_DIRECTION, Constants.DIRECTION_OUTBOUND);
                    }
                    sslProps = getProperties(null, currentConnectionInfo, null);
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Getting SSLSocketFactory");
                    currentFactory = getSSLSocketFactory(currentConnectionInfo, sslProps);
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Got SSLSocketFactory", new Object[] { currentFactory });
                } else {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Neither SSLProperties nor outboundConnectionInfo is set and this is an unconnected socket so create a WSSocket.");
                    java.net.Socket ws_socket = (Socket) AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {

                            return (new com.ibm.ws.ssl.config.WSSocket(new java.net.Socket()));
                        }
                    });
                    if (tc.isEntryEnabled())
                        Tr.exit(tc, "createSocket");
                    return ws_socket;
                }

            } catch (Exception e) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Exception getting SSLSocketFactory. Fall back to the default SSLSocketFactory", new Object[] { e });
                FFDCFilter.processException(e, getClass().getName(), "createSocket", this);
                currentFactory = default_factory;
            }
        } else {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Use default SSLSocketFactory - the default constructor was not used");
        }
        if (currentFactory != null) {
            socket = (javax.net.ssl.SSLSocket) currentFactory.createSocket();
            socket = SSLConfigManager.getInstance().setCipherListOnSocket(sslProps, socket);
        } else
            throw new javax.net.ssl.SSLException("SSLSocketFactory is null. This can occur if javax.net.ssl.SSLSocketFactory.getDefault() is called to create a socket and javax.net.ssl.* properties are not set.");

        if (tc.isEntryEnabled())
            Tr.exit(tc, "createSocket");
        return socket;
    }
1040271
@Override
    protected void doStart() throws Exception
    {
        log.info("starting...");
        super.doStart();
        _client = newClient(_serverString);
        if (_client == null)
        {
            throw new IllegalStateException("newClient(" + _serverString + ") returns null.");
        }
        log.info("use " + _client.getClass().getSimpleName() + " as client factory.");
        _client.establish();
        log.info("started.");
    }
695176
public ServletOutputStream getOutputStream() 
    {
        if (_outputState==DISABLED)
            return __nullServletOut;
        
        if (_outputState!=NO_OUT && _outputState!=OUTPUTSTREAM_OUT)
            throw new IllegalStateException();
        
        if (_writer!=null)
        {
            _writer.flush();
            _writer.disable();
            _writer=null;
        }
        
        if (_out==null)
            _out = new ServletOut(_servletHttpRequest.getHttpRequest()
                                  .getOutputStream());  
        _outputState=OUTPUTSTREAM_OUT;
        return _out;
    }
747431
public boolean getRTS() throws IllegalStateException, IOException{
        // validate state
        if (isClosed())
            throw new IllegalStateException("Serial connection is not open; cannot 'getRTS()'.");

        // get pin state
        return com.pi4j.jni.Serial.getRTS(fileDescriptor);
    }