@@ -884,20 +884,25 @@ public void init() throws Exception {
884884
885885 /*
886886 * Get connection.
887- * Use counter (getConnectionTurn) that increments on each connection access
888- * to ensure random distribution of connections, regardless of expired connections.
887+ * Use counter (getConnectionTurn) that increments on each call to ensure random distribution.
888+ * Guarantees to return a valid connection if one exists, and avoids multiple threads
889+ * getting the same connection even when there are consecutive expired connections.
889890 */
890891 public ObTableConnection getConnection () {
891892 ObTableConnection [] connections = connectionPool .get ();
893+
894+
895+ // Get starting position from counter (increments on each call for randomness)
896+ long startTurn = getConnectionTurn .getAndIncrement ();
897+ if (startTurn == Long .MAX_VALUE ) {
898+ getConnectionTurn .set (0 );
899+ }
900+ int startIdx = (int ) (startTurn % connections .length );
892901
893- // Start from current counter position and find first valid connection
894- // Increment counter for each connection accessed
902+ // Traverse all connections starting from startIdx to guarantee finding a valid one
903+ // This ensures we check all connections if needed, avoiding null return
895904 for (int i = 0 ; i < connections .length ; i ++) {
896- long nextTurn = getConnectionTurn .getAndIncrement ();
897- if (nextTurn == Long .MAX_VALUE ) {
898- getConnectionTurn .set (0 );
899- }
900- int idx = (int ) (nextTurn % connections .length );
905+ int idx = (startIdx + i ) % connections .length ;
901906 if (!connections [idx ].isExpired ()) {
902907 return connections [idx ];
903908 }
@@ -982,6 +987,9 @@ private void checkAndReconnect() {
982987 }
983988 }
984989
990+ // Shuffle the expired connection indices to avoid consecutive connections
991+ Collections .shuffle (expiredConnIds );
992+
985993 // Mark a third of the expired connections for reconnection
986994 int needReconnectCount = (int ) Math .ceil (expiredConnIds .size () / 3.0 );
987995 for (int i = 0 ; i < needReconnectCount ; i ++) {
0 commit comments