return (AsyncMethodCallback<?>) args[args.length - 1];
}
private TAsyncClient newClient(Class<?> c, Connection connection) throws InterruptedException {
BlockingQueue<TAsyncClient> blockingQueue = getQueue(connection);
TAsyncClient client = blockingQueue.poll();
if (client != null) {
return client;
}
AtomicInteger counter;
synchronized (_numberOfConnections) {
counter = _numberOfConnections.get(connection.getHost());
if (counter == null) {
counter = new AtomicInteger();
_numberOfConnections.put(connection.getHost(), counter);
}
}
synchronized (counter) {
int numOfConnections = counter.get();
while (numOfConnections >= _maxConnectionsPerHost) {
client = blockingQueue.poll(_pollTime, TimeUnit.MILLISECONDS);
if (client != null) {
return client;
}
LOG.debug("Waiting for client number of connection [" + numOfConnections + "], max connection per host [" + _maxConnectionsPerHost + "]");
numOfConnections = counter.get();
}
LOG.info("Creating a new client for [" + connection + "]");
String name = c.getName();
Constructor<?> constructor = _constructorCache.get(name);
if (constructor == null) {
String clientClassName = name.replace("$AsyncIface", "$AsyncClient");
try {
Class<?> clazz = Class.forName(clientClassName);
constructor = clazz.getConstructor(new Class[] { TProtocolFactory.class, TAsyncClientManager.class, TNonblockingTransport.class });
_constructorCache.put(name, constructor);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
TNonblockingSocket transport = newTransport(connection);
client = (TAsyncClient) constructor.newInstance(new Object[] { _protocolFactory, _clientManager, transport });
client.setTimeout(_timeout);
counter.incrementAndGet();
return client;
} catch (Exception e) {
throw new RuntimeException(e);
}