lib/stillwater/connection_pool.rb in stillwater-0.0.2 vs lib/stillwater/connection_pool.rb in stillwater-0.0.3
- old
+ new
@@ -6,22 +6,20 @@
def initialize
@pool = []
@reactivate_timeout = 5 * 60 # 5 minutes
@retry_count = 3
+ @polling = false
end
def add(&builder)
@pool << connection_info_from(builder)
end
def reactivate_timeout=(seconds)
- running = !!@thread
- @thread.kill if running
- @thread = nil
@reactivate_timeout = seconds
- start_polling if running
+ start_polling
end
def with_connection(&block)
conn = checkout
result = yield conn
@@ -30,22 +28,25 @@
result
end
def retry_connection_from(exception_class, &block)
count = 0
- conn = checkout
- yield conn
- rescue exception_class
- deactivate conn
- count += 1
- raise if count >= @retry_count
- retry
- ensure
- checkin conn
+ begin
+ conn = checkout
+ yield conn
+ rescue exception_class
+ raise if count >= @retry_count
+ deactivate conn
+ count += 1
+ retry
+ ensure
+ checkin conn
+ end
end
def checkout
+ reactivate_all if poll_timeout_exceeded?
connection_info = available.respond_to?(:sample) ? available.sample : available.choice
raise ConnectionNotAvailable if connection_info.nil?
connection_info[:state] = :in_use
connection_info[:connection]
@@ -88,14 +89,21 @@
in_use.size
end
private
- def start_polling
- @thread ||= Thread.new do
- sleep @reactivate_timeout
- reactivate_all
+ def poll_timeout_exceeded?
+ return false unless @polling
+ now = Time.now
+ if (now - @last_poll_time) >= @reactivate_timeout
+ @last_poll_time = now
+ true
end
+ end
+
+ def start_polling
+ @polling = true
+ @last_poll_time = Time.now
end
def available
find_by_state :available
end