Skip to content

Commit f9230a2

Browse files
committed
Merge pull request rails#27057 from kamipo/fix_race_condition
Fix the race condition caused by `with_new_connections_blocked`
2 parents ff2fe01 + 700639e commit f9230a2

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -350,8 +350,7 @@ def initialize(spec)
350350
# currently in the process of independently establishing connections to the DB.
351351
@now_connecting = 0
352352

353-
# A boolean toggle that allows/disallows new connections.
354-
@new_cons_enabled = true
353+
@threads_blocking_new_connections = 0
355354

356355
@available = ConnectionLeasingQueue.new self
357356
end
@@ -700,13 +699,15 @@ def checkout_for_exclusive_access(checkout_timeout)
700699
end
701700

702701
def with_new_connections_blocked
703-
previous_value = nil
704702
synchronize do
705-
previous_value, @new_cons_enabled = @new_cons_enabled, false
703+
@threads_blocking_new_connections += 1
706704
end
705+
707706
yield
708707
ensure
709-
synchronize { @new_cons_enabled = previous_value }
708+
synchronize do
709+
@threads_blocking_new_connections -= 1
710+
end
710711
end
711712

712713
# Acquire a connection by one of 1) immediately removing one
@@ -758,7 +759,7 @@ def try_to_checkout_new_connection
758759
# and increment @now_connecting, to prevent overstepping this pool's @size
759760
# constraint
760761
do_checkout = synchronize do
761-
if @new_cons_enabled && (@connections.size + @now_connecting) < @size
762+
if @threads_blocking_new_connections.zero? && (@connections.size + @now_connecting) < @size
762763
@now_connecting += 1
763764
end
764765
end

0 commit comments

Comments
 (0)