创建原始连接的方法

@throws ThriftConnectionPoolException
创建连接出现问题时抛出该异常
559842
@SuppressWarnings("unchecked")
	private void createConnection() throws ThriftConnectionPoolException {
		try {
			transport = new TSocket(host, port, connectionTimeOut);
			transport.open();
			TProtocol protocol = createTProtocol(transport);

			Iterator<Entry<String, Class<? extends TServiceClient>>> iterator = thriftClientClasses.entrySet()
					.iterator();
			while (iterator.hasNext()) {
				Entry<String, Class<? extends TServiceClient>> entry = iterator.next();
				String serviceName = entry.getKey();
				Class<? extends TServiceClient> clientClass = entry.getValue();
				TMultiplexedProtocol multiProtocol = new TMultiplexedProtocol(protocol, serviceName);
				// 反射实例化客户端对象
				Constructor<? extends TServiceClient> clientConstructor = clientClass.getConstructor(TProtocol.class);
				T client = (T) clientConstructor.newInstance(multiProtocol);
				clients.put(serviceName, client);
				if (logger.isDebugEnabled()) {
					logger.debug("创建新连接成功:" + host + " 端口：" + port);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ThriftConnectionPoolException("无法连接服务器：" + host + " 端口：" + port, e);
		}
	}
1334586
public void yieldConnection(Connection con) throws FetchException {
        try {
            if (con.getAutoCommit()) {
                closeConnection(con);
            }
            // Connections which aren't auto-commit are in a transaction. Keep
            // them around instead of closing them.
        } catch (Exception e) {
            throw toFetchException(e);
        }
    }
632921
@Override
	public ThriftConnection<T> pollConnection() {
		ThriftConnection<T> result;
		if (pool.getThriftServerCount() == 0) {
			throw new IllegalStateException("当前无可用连接服务器");
		}
		int partition = (int) (Thread.currentThread().getId() % this.pool.thriftServerCount);

		ThriftConnectionPartition<T> thriftConnectionPartition = this.pool.partitions.get(partition);

		result = thriftConnectionPartition.poolFreeConnection();
		if (result == null) {
			for (int i = 0; i < this.pool.thriftServerCount; i++) {
				if (i == partition) {
					continue;
				}
				result = this.pool.partitions.get(i).poolFreeConnection();
				if (result != null) {
					thriftConnectionPartition = this.pool.partitions.get(i);
					break;
				}
			}
		}

		if (!thriftConnectionPartition.isUnableToCreateMoreTransactions()) {
			this.pool.maybeSignalForMoreConnections(thriftConnectionPartition);
		}
		return result;
	}
178837
public static synchronized void getConnectionListener(String poolName, Object mcp, Object cl,
                                                         boolean pooled, boolean interleaving,
                                                         Throwable callstack)
   {
      if (!interleaving)
      {
         if (pooled)
         {
            log.tracef("%s", new TraceEvent(poolName, Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_CONNECTION_LISTENER,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
         else
         {
            log.tracef("%s", new TraceEvent(poolName,
                                            Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_CONNECTION_LISTENER_NEW,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
      }
      else
      {
         if (pooled)
         {
            log.tracef("%s", new TraceEvent(poolName,
                                            Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_INTERLEAVING_CONNECTION_LISTENER,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
         else
         {
            log.tracef("%s", new TraceEvent(poolName,
                                            Integer.toHexString(System.identityHashCode(mcp)),
                                            TraceEvent.GET_INTERLEAVING_CONNECTION_LISTENER_NEW,
                                            Integer.toHexString(System.identityHashCode(cl)),
                                            !confidential && callstack != null ? toString(callstack) : ""));
         }
      }
   }
1358248
@Override
	public synchronized void releaseAllThriftSocket() {
		if (selfMap == null || selfMap.isEmpty())
			return;
		ThriftSocket socket;
		for (Entry<String, SimpleSocketPoolImpl> entry : selfMap.entrySet()) {
			SimpleSocketPoolImpl self = entry.getValue();
			for (byte i = 0; i < size; i++) {
				socket = self.socketPool.get(new Byte(i));
				try {
					socket.close();
					self.socketStatusArray[i] = Boolean.FALSE;
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			}
		}
	}
1292098
public void internalClose() throws ThriftConnectionPoolException {
		try {
			if (this.thriftConnection != null) {
				this.thriftConnection.close();
			}
			logicallyClosed.set(true);
		} catch (IOException e) {
			throw new ThriftConnectionPoolException(e);
		}
	}
237821
@Override
	protected void initServer(TServerTransport serverTransport) {
		ThriftServerConfiguration configuration = getServerConfiguration();
		// 使用多线程半同步半异步方式
		TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args((TNonblockingServerSocket) serverTransport)
				.transportFactory(configuration.getTransportFactory())
				.protocolFactory(configuration.getProtocolFactory());
		if (configuration.getExecutorService() != null)
			args.executorService(configuration.getExecutorService());
		server = new TThreadedSelectorServer(
				configuration.getServerArgsAspect().tThreadedSelectorServerArgsAspect(args).processor(getProcessor()));
		if (configuration.getServerEventHandler() != null)
			server.setServerEventHandler(configuration.getServerEventHandler());
	}
1078461
public static <T> T run(HTablePool pool, byte[] tableName, HTableRunnable<T> runnable)
            throws IOException {
        HTableInterface hTable = null;
        try {
            hTable = pool.getTable(tableName);
            return runnable.runWith(hTable);
        } catch (Exception e) {
            if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            if (hTable != null) {
                pool.putTable(hTable);
            }
        }
    }
779558
public void train() throws Exception {

		loadData();
		/**
		 * 
		 * 更新参数的准则
		 */
		Update update;
		// viterbi解码
		Inferencer inference;

		HammingLoss loss = new HammingLoss();
		if (standard) {
			inference = new LinearViterbi(templets, labels.size());
			update = new LinearViterbiPAUpdate((LinearViterbi) inference, loss);
		} else {
			inference = new HigherOrderViterbi(templets, labels.size());
			update = new HigherOrderViterbiPAUpdate(templets, labels.size(), true);
		}

		OnlineTrainer trainer;

		if(cl!=null){
			trainer = new OnlineTrainer(cl, update, loss, factory,iterNum, c);
		}else{
			trainer = new OnlineTrainer(inference, update, loss,
					factory, iterNum, c);
		}

		cl = trainer.train(trainSet, testSet);

		if(cl!=null&&newmodel!=null)
			saveTo(newmodel);
		else
			saveTo(model);

	}
999355
public ThriftConnection<T> obtainInternalConnection(ThriftConnectionHandle<T> thriftConnectionHandle)
			throws ThriftConnectionPoolException {
		boolean tryAgain;
		ThriftConnection<T> result;
		ThriftConnection<T> oldRawConnection = thriftConnectionHandle.getInternalConnection();
		ThriftServerInfo thriftServerInfo = thriftConnectionHandle.getThriftServerInfo();

		int acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts();
		long acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs();
		AcquireFailConfig acquireConfig = new AcquireFailConfig();
		acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));
		acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs);
		acquireConfig.setLogMessage("Failed to acquire connection to " + thriftServerInfo.toString());

		do {
			result = null;

			try {
				// 尝试获取原始连接
				result = this.obtainRawInternalConnection(thriftServerInfo);
				tryAgain = false;

				if (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()) {
					logger.info("Successfully re-established connection to " + thriftServerInfo.toString());
				}

				thriftConnectionHandle.getConnectionPartition().getServerIsDown().set(false);

				thriftConnectionHandle.setInternalConnection(result);

			} catch (ThriftConnectionPoolException e) {
				logger.error(String.format("Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d",
						thriftServerInfo.toString(), acquireRetryDelayInMs, acquireRetryAttempts), e);

				try {
					if (acquireRetryAttempts > 0) {
						Thread.sleep(acquireRetryDelayInMs);
					}
					tryAgain = (acquireRetryAttempts--) > 0;
				} catch (InterruptedException e1) {
					tryAgain = false;
				}

				if (!tryAgain) {
					if (oldRawConnection != null) {
						try {
							oldRawConnection.close();
						} catch (IOException e1) {
							throw new ThriftConnectionPoolException(e1);
						}
					}
					thriftConnectionHandle.setInternalConnection(oldRawConnection);
					throw e;
				}

			}
		} while (tryAgain);
		return result;
	}
838014
@Override
	protected void onClosed() {
		assert promise == null;
		if (pool == client.poolKeepAlive) {
			AddressLinkedList addresses = client.addresses.get(remoteAddress);
			addresses.removeNode(this);
			if (addresses.isEmpty()) {
				client.addresses.remove(remoteAddress);
			}
		}

		// pool will be null if socket was closed by the value just before connection.send() invocation
		// (eg. if connection was in open(null) or taken(null) states)
		pool.removeNode(this);
		pool = null;

		client.onConnectionClosed();
		if (response != null) {
			response.recycle();
			response = null;
		}
	}
756784
void indexPool() throws BadClassFile {
        poolIdx = new int[nextChar()];
        int i = 1;
        while (i < poolIdx.length) {
            poolIdx[i++] = bp;
            byte tag = buf[bp++];
            switch (tag) {
            case CONSTANT_Utf8: case CONSTANT_Unicode: {
                int len = nextChar();
                bp = bp + len;
                break;
            }
            case CONSTANT_Class:
            case CONSTANT_String:
            case CONSTANT_MethodType:
            case CONSTANT_Module:
            case CONSTANT_Package:
                bp = bp + 2;
                break;
            case CONSTANT_MethodHandle:
                bp = bp + 3;
                break;
            case CONSTANT_Fieldref:
            case CONSTANT_Methodref:
            case CONSTANT_InterfaceMethodref:
            case CONSTANT_NameandType:
            case CONSTANT_Integer:
            case CONSTANT_Float:
            case CONSTANT_InvokeDynamic:
                bp = bp + 4;
                break;
            case CONSTANT_Long:
            case CONSTANT_Double:
                bp = bp + 8;
                i++;
                break;
            default:
                throw new BadClassFile("malformed constant pool");
            }
        }
    }
1182874
protected void storeXaPool(DsXaPool pool, XMLStreamWriter writer) throws Exception
   {
      writer.writeStartElement(XML.ELEMENT_XA_POOL);

      if (pool.getMinPoolSize() != null && (pool.hasExpression(XML.ELEMENT_MIN_POOL_SIZE) ||
                                            !Defaults.MIN_POOL_SIZE.equals(pool.getMinPoolSize())))
      {
         writer.writeStartElement(XML.ELEMENT_MIN_POOL_SIZE);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_MIN_POOL_SIZE, pool.getMinPoolSize().toString()));
         writer.writeEndElement();
      }

      if (pool.getInitialPoolSize() != null)
      {
         writer.writeStartElement(XML.ELEMENT_INITIAL_POOL_SIZE);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_INITIAL_POOL_SIZE, pool.getInitialPoolSize().toString()));
         writer.writeEndElement();
      }

      if (pool.getMaxPoolSize() != null && (pool.hasExpression(XML.ELEMENT_MAX_POOL_SIZE) ||
                                            !Defaults.MAX_POOL_SIZE.equals(pool.getMaxPoolSize())))
      {
         writer.writeStartElement(XML.ELEMENT_MAX_POOL_SIZE);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_MAX_POOL_SIZE, pool.getMaxPoolSize().toString()));
         writer.writeEndElement();
      }

      if (pool.isPrefill() != null && (pool.hasExpression(XML.ELEMENT_PREFILL) ||
                                       !Defaults.PREFILL.equals(pool.isPrefill())))
      {
         writer.writeStartElement(XML.ELEMENT_PREFILL);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_PREFILL, pool.isPrefill().toString()));
         writer.writeEndElement();
      }

      if (pool.getFlushStrategy() != null && (pool.hasExpression(XML.ELEMENT_FLUSH_STRATEGY) ||
                                              !Defaults.FLUSH_STRATEGY.equals(pool.getFlushStrategy())))
      {
         writer.writeStartElement(XML.ELEMENT_FLUSH_STRATEGY);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_FLUSH_STRATEGY, pool.getFlushStrategy().toString()));
         writer.writeEndElement();
      }

      if (pool.getCapacity() != null)
         storeCapacity(pool.getCapacity(), writer);

      if (pool.getConnectionListener() != null)
      {
         storeExtension(pool.getConnectionListener(), writer, XML.ELEMENT_CONNECTION_LISTENER);
      }

      if (pool.isIsSameRmOverride() != null)
      {
         writer.writeStartElement(XML.ELEMENT_IS_SAME_RM_OVERRIDE);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_IS_SAME_RM_OVERRIDE, pool.isIsSameRmOverride().toString()));
         writer.writeEndElement();
      }

      if (pool.isPadXid() != null && (pool.hasExpression(XML.ELEMENT_PAD_XID) ||
                                      !Defaults.PAD_XID.equals(pool.isPadXid())))
      {
         writer.writeStartElement(XML.ELEMENT_PAD_XID);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_PAD_XID, pool.isPadXid().toString()));
         writer.writeEndElement();
      }

      if (pool.isWrapXaResource() != null && (pool.hasExpression(XML.ELEMENT_WRAP_XA_RESOURCE) ||
                                              !Defaults.WRAP_XA_RESOURCE.equals(pool.isWrapXaResource())))
      {
         writer.writeStartElement(XML.ELEMENT_WRAP_XA_RESOURCE);
         writer.writeCharacters(pool.getValue(XML.ELEMENT_WRAP_XA_RESOURCE, pool.isWrapXaResource().toString()));
         writer.writeEndElement();
      }

      writer.writeEndElement();
   }
878542
synchronized int cleanPools() {
        int totalConnectionsRemaining = 0;
        List<String> hostsToRemove = new ArrayList<String>();
        for (Map.Entry<String, TransportPool> hostPool : hostPools.entrySet()) {
            String host = hostPool.getKey();
            TransportPool pool = hostPool.getValue();

            int connectionsRemaining = pool.removeOldConnections();
            if (connectionsRemaining == 0) {
                hostsToRemove.add(host);
            } else {
                totalConnectionsRemaining += connectionsRemaining;
            }
        }

        // Remove old pools that now have no connections.
        for (String hostToRemove : hostsToRemove) {
            hostPools.remove(hostToRemove);
        }

        return totalConnectionsRemaining;
    }
628405
private static void initExceptionThreadPool() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "initExceptionThreadPool");

        // Do a synchronous check to ensure once-only creation
        synchronized (exceptionTPCreateSync) {
            if (exceptionThreadPool == null) {
                // Get the maximum size for the thread pool, defaulting if
                // not specified or if the value cannot be parsed
                int maxThreads = Integer.parseInt(ApiJmsConstants.EXCEPTION_MAXTHREADS_DEFAULT_INT);
                String maxThreadsStr = RuntimeInfo.getProperty(ApiJmsConstants.EXCEPTION_MAXTHREADS_NAME_INT,
                                                               ApiJmsConstants.EXCEPTION_MAXTHREADS_DEFAULT_INT);
                try {
                    maxThreads = Integer.parseInt(maxThreadsStr);
                } catch (NumberFormatException e) {
                    // No FFDC code needed, but we will exception this
                    SibTr.exception(tc, e);
                }

                // Trace the value we will use
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(tc, ApiJmsConstants.EXCEPTION_MAXTHREADS_NAME_INT + ": " + Integer.toString(maxThreads));

                // Create the thread pool
                exceptionThreadPool = new ThreadPool(ApiJmsConstants.EXCEPTION_THREADPOOL_NAME_INT, 0, maxThreads);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "initExceptionThreadPool");
    }
698552
public Db tx(TransactionLevel transactionLevel, VoidFunc1<Db> func) throws SQLException {
		final Connection conn = getConnection();

		// 检查是否支持事务
		checkTransactionSupported(conn);

		// 设置事务级别
		if (null != transactionLevel) {
			final int level = transactionLevel.getLevel();
			if (conn.getTransactionIsolation() < level) {
				// 用户定义的事务级别如果比默认级别更严格，则按照严格的级别进行
				conn.setTransactionIsolation(level);
			}
		}

		// 开始事务
		boolean autoCommit = conn.getAutoCommit();
		if (autoCommit) {
			conn.setAutoCommit(false);
		}

		// 执行事务
		try {
			func.call(this);
			// 提交
			conn.commit();
		} catch (Throwable e) {
			quietRollback(conn);
			throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e);
		} finally {
			// 还原事务状态
			quietSetAutoCommit(conn, autoCommit);
			// 关闭连接或将连接归还连接池
			closeConnection(conn);
		}

		return this;
	}
1349823
function initConnectionPool() {

  var setting = {
    hostname: config.oracle.host,
    port    : config.oracle.port,
    database: config.oracle.dbname,
    user    : config.oracle.user,
    password: config.oracle.pass,
    pool    : {
      name: "oracle",
      log : false,
      max : config.oracle.pool
    }
  };

  console.log("Oracle code: " + setting.database);
  console.log("Oracle host: " + setting.hostname);
  console.log("Oracle port: " + setting.port);
  console.log("Oracle pool: " + setting.pool.max);
  console.log("Oracle user: " + setting.user);

  return generic.Pool({
    name   : setting.pool.name,
    log    : setting.pool.log,
    max    : setting.pool.max,
    create : function (callback) {
      oracle().connect(setting, function (err, connection) {
        callback(err, connection);
      });
    },
    destroy: function (connection) {
      connection.close();
    }
  });
}