Permalink
Browse files

introduce a timer class for reaping connections

  • Loading branch information...
1 parent cceabe0 commit cde7692d4e3e0e67e480cc6172f6e2bacaceeb5e @tenderlove tenderlove committed Dec 30, 2011
View
19 activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -64,6 +64,25 @@ module ConnectionAdapters
# * +wait_timeout+: number of seconds to block and wait for a connection
# before giving up and raising a timeout error (default 5 seconds).
class ConnectionPool
+ class Reaper
+ attr_reader :pool, :frequency
+
+ def initialize(pool, frequency)
+ @pool = pool
+ @frequency = frequency
+ end
+
+ def start
+ return unless frequency
+ Thread.new(frequency, pool) { |t, p|
+ while true
@sobrinho
sobrinho added a line comment Dec 31, 2011

could be loop :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ sleep t
+ p.reap
+ end
+ }
+ end
+ end
+
include MonitorMixin
attr_accessor :automatic_reconnect, :timeout
View
46 activerecord/test/cases/reaper_test.rb
@@ -0,0 +1,46 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ReaperTest < ActiveRecord::TestCase
+ attr_reader :pool
+
+ def setup
+ super
+ @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ end
+
+ def teardown
+ super
+ @pool.connections.each(&:close)
+ end
+
+ # A reaper with nil time should never reap connections
+ def test_nil_time
+ conn = pool.checkout
+ pool.timeout = 0
+
+ count = pool.connections.length
+ conn.extend(Module.new { def active?; false; end; })
+
+ reaper = ConnectionPool::Reaper.new(pool, nil)
+ reaper.start
+ sleep 0.0001
+ assert_equal count, pool.connections.length
+ end
+
+ def test_some_time
+ conn = pool.checkout
+ pool.timeout = 0
+
+ count = pool.connections.length
+ conn.extend(Module.new { def active?; false; end; })
+
+ reaper = ConnectionPool::Reaper.new(pool, 0.0001)
+ reaper.start
+ sleep 0.0002
+ assert_equal(count - 1, pool.connections.length)
+ end
+ end
+ end
+end

0 comments on commit cde7692

Please sign in to comment.