Skip to content

Commit 84a66b9

Browse files
committed
refactor idle reaping for readability
1 parent e7825d6 commit 84a66b9

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

lib/connection_pool/timed_stack.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ def push(obj, **)
5858
# @option options [Class] :exception (ConnectionPool::TimeoutError) Exception class to raise
5959
# if an entry was not available within the timeout period. Use `exception: false` to return nil.
6060
#
61-
# The +timeout+ argument will be removed in 3.0.
6261
# Other options may be used by subclasses that extend TimedStack.
6362
def pop(timeout: 0.5, exception: ConnectionPool::TimeoutError, **)
6463
deadline = current_time + timeout
@@ -109,7 +108,8 @@ def reap(idle_seconds:)
109108
raise ArgumentError, "idle_seconds must be a number" unless idle_seconds.is_a?(Numeric)
110109
raise ConnectionPool::PoolShuttingDownError if @shutdown_block
111110

112-
idle.times do
111+
count = idle
112+
count.times do
113113
conn = @mutex.synchronize do
114114
raise ConnectionPool::PoolShuttingDownError if @shutdown_block
115115
reserve_idle_connection(idle_seconds)
@@ -197,6 +197,8 @@ def reserve_idle_connection(idle_seconds)
197197

198198
@created -= 1 unless @created == 0
199199

200+
# Most active elements are at the tail of the array.
201+
# Most idle will be at the head so `shift` rather than `pop`.
200202
@que.shift.first
201203
end
202204

@@ -205,7 +207,10 @@ def reserve_idle_connection(idle_seconds)
205207
#
206208
# Returns true if the first connection in the stack has been idle for more than idle_seconds
207209
def idle_connections?(idle_seconds)
208-
connection_stored? && (current_time - @que.first.last > idle_seconds)
210+
return unless connection_stored?
211+
# Most idle will be at the head so `first`
212+
age = (current_time - @que.first.last)
213+
age > idle_seconds
209214
end
210215

211216
##

test/test_connection_pool.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,7 @@ def test_shutdown_is_executed_for_all_connections
510510

511511
kill_threads(threads)
512512

513-
assert_equal [["shutdown"]] * 3, recorders.map { |r| r.calls }
513+
assert_equal %w[shutdown shutdown shutdown], recorders.map { |r| r.calls }.flatten
514514
end
515515

516516
def test_checkout_after_reload_cannot_create_new_connections_beyond_size

0 commit comments

Comments
 (0)