Skip to content

Commit ca3dec8

Browse files
committed
HostConnectionPool: use connection for any shard
if connections for a target shard are still being initialized. Signed-off-by: Piotr Jastrzebski <haaawk@gmail.com>
1 parent daf1b6f commit ca3dec8

1 file changed

Lines changed: 26 additions & 11 deletions

File tree

driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,19 @@ private PoolingOptions options() {
319319
return manager.configuration().getPoolingOptions();
320320
}
321321

322+
private Connection findLeastBusyForShard(int shardId) {
323+
int minInFlight = Integer.MAX_VALUE;
324+
Connection result = null;
325+
for (Connection connection : connections[shardId]) {
326+
int inFlight = connection.inFlight.get();
327+
if (inFlight < minInFlight) {
328+
minInFlight = inFlight;
329+
result = connection;
330+
}
331+
}
332+
return result;
333+
}
334+
322335
ListenableFuture<Connection> borrowConnection(
323336
long timeout, TimeUnit unit, int maxQueueSize, ByteBuffer routingKey) {
324337
Phase phase = this.phase.get();
@@ -337,29 +350,31 @@ ListenableFuture<Connection> borrowConnection(
337350
}
338351
}
339352

353+
Connection leastBusy = null;
354+
340355
if (connections[shardId].isEmpty()) {
341356
if (host.convictionPolicy.canReconnectNow()) {
342357
if (connectionsPerShard == 0) {
343358
maybeSpawnNewConnection(shardId);
359+
return enqueue(timeout, unit, maxQueueSize, shardId);
344360
} else if (scheduledForCreation[shardId].compareAndSet(0, connectionsPerShard)) {
345361
for (int i = 0; i < connectionsPerShard; i++) {
346362
// We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
347363
// protect against creating connection in excess of core too quickly
348364
manager.blockingExecutor().submit(new ConnectionTask(shardId));
349365
}
366+
return enqueue(timeout, unit, maxQueueSize, shardId);
350367
}
351-
return enqueue(timeout, unit, maxQueueSize, shardId);
352-
}
353-
}
354-
355-
int minInFlight = Integer.MAX_VALUE;
356-
Connection leastBusy = null;
357-
for (Connection connection : connections[shardId]) {
358-
int inFlight = connection.inFlight.get();
359-
if (inFlight < minInFlight) {
360-
minInFlight = inFlight;
361-
leastBusy = connection;
362368
}
369+
// connections for this shard are still being initialized so pick connection for any shard
370+
int firstShardToCheck = RAND.nextInt(connections.length);
371+
int shardToCheck = firstShardToCheck;
372+
do {
373+
leastBusy = findLeastBusyForShard(shardToCheck);
374+
shardToCheck = (shardToCheck + 1) % connections.length;
375+
} while (leastBusy == null && shardToCheck != firstShardToCheck);
376+
} else {
377+
leastBusy = findLeastBusyForShard(shardId);
363378
}
364379

365380
if (leastBusy == null) {

0 commit comments

Comments
 (0)