Skip to content

Commit 92b3160

Browse files
authored
Merge pull request rails#54052 from SjoerdL/check-pinned-connection-in-checkout
Fix race condition in ConnectionPool#checkout on @pinned_connection
2 parents 2eec91b + b7a5dc4 commit 92b3160

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -545,20 +545,25 @@ def clear_reloadable_connections!
545545
# Raises:
546546
# - ActiveRecord::ConnectionTimeoutError no connection can be obtained from the pool.
547547
def checkout(checkout_timeout = @checkout_timeout)
548-
if @pinned_connection
549-
@pinned_connection.lock.synchronize do
550-
synchronize do
548+
return checkout_and_verify(acquire_connection(checkout_timeout)) unless @pinned_connection
549+
550+
@pinned_connection.lock.synchronize do
551+
synchronize do
552+
# The pinned connection may have been cleaned up before we synchronized, so check if it is still present
553+
if @pinned_connection
551554
@pinned_connection.verify!
555+
552556
# Any leased connection must be in @connections otherwise
553557
# some methods like #connected? won't behave correctly
554558
unless @connections.include?(@pinned_connection)
555559
@connections << @pinned_connection
556560
end
561+
562+
@pinned_connection
563+
else
564+
checkout_and_verify(acquire_connection(checkout_timeout))
557565
end
558566
end
559-
@pinned_connection
560-
else
561-
checkout_and_verify(acquire_connection(checkout_timeout))
562567
end
563568
end
564569

0 commit comments

Comments
 (0)