Skip to content
This repository
Browse code

introduce a timer class for reaping connections

  • Loading branch information...
commit cde7692d4e3e0e67e480cc6172f6e2bacaceeb5e 1 parent cceabe0
Aaron Patterson tenderlove authored
19 activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -64,6 +64,25 @@ module ConnectionAdapters
64 64 # * +wait_timeout+: number of seconds to block and wait for a connection
65 65 # before giving up and raising a timeout error (default 5 seconds).
66 66 class ConnectionPool
  67 + class Reaper
  68 + attr_reader :pool, :frequency
  69 +
  70 + def initialize(pool, frequency)
  71 + @pool = pool
  72 + @frequency = frequency
  73 + end
  74 +
  75 + def start
  76 + return unless frequency
  77 + Thread.new(frequency, pool) { |t, p|
  78 + while true
  79 + sleep t
  80 + p.reap
  81 + end
  82 + }
  83 + end
  84 + end
  85 +
67 86 include MonitorMixin
68 87
69 88 attr_accessor :automatic_reconnect, :timeout
46 activerecord/test/cases/reaper_test.rb
... ... @@ -0,0 +1,46 @@
  1 +require "cases/helper"
  2 +
  3 +module ActiveRecord
  4 + module ConnectionAdapters
  5 + class ReaperTest < ActiveRecord::TestCase
  6 + attr_reader :pool
  7 +
  8 + def setup
  9 + super
  10 + @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
  11 + end
  12 +
  13 + def teardown
  14 + super
  15 + @pool.connections.each(&:close)
  16 + end
  17 +
  18 + # A reaper with nil time should never reap connections
  19 + def test_nil_time
  20 + conn = pool.checkout
  21 + pool.timeout = 0
  22 +
  23 + count = pool.connections.length
  24 + conn.extend(Module.new { def active?; false; end; })
  25 +
  26 + reaper = ConnectionPool::Reaper.new(pool, nil)
  27 + reaper.start
  28 + sleep 0.0001
  29 + assert_equal count, pool.connections.length
  30 + end
  31 +
  32 + def test_some_time
  33 + conn = pool.checkout
  34 + pool.timeout = 0
  35 +
  36 + count = pool.connections.length
  37 + conn.extend(Module.new { def active?; false; end; })
  38 +
  39 + reaper = ConnectionPool::Reaper.new(pool, 0.0001)
  40 + reaper.start
  41 + sleep 0.0002
  42 + assert_equal(count - 1, pool.connections.length)
  43 + end
  44 + end
  45 + end
  46 +end

0 comments on commit cde7692

Please sign in to comment.
Something went wrong with that request. Please try again.