Skip to content

Commit

Permalink
Merge pull request #36345 from jhawthorn/weakref_reaper
Browse files Browse the repository at this point in the history
Use WeakRef in Reaper to avoid leaking connection pools
  • Loading branch information
rafaelfranca committed May 27, 2019
2 parents b55f5a3 + 6302e56 commit 1da0e25
Showing 1 changed file with 21 additions and 11 deletions.
Expand Up @@ -3,6 +3,7 @@
require "thread"
require "concurrent/map"
require "monitor"
require "weakref"

module ActiveRecord
# Raised when a connection could not be obtained within the connection
Expand Down Expand Up @@ -294,28 +295,37 @@ def initialize(pool, frequency)
@frequency = frequency
end

@@mutex = Mutex.new
@@pools = {}
@mutex = Mutex.new
@pools = {}

def self.register_pool(pool, frequency) # :nodoc:
@@mutex.synchronize do
if @@pools.key?(frequency)
@@pools[frequency] << pool
else
@@pools[frequency] = [pool]
class << self
def register_pool(pool, frequency) # :nodoc:
@mutex.synchronize do
unless @pools.key?(frequency)
@pools[frequency] = []
spawn_thread(frequency)
end
@pools[frequency] << WeakRef.new(pool)
end
end

private

def spawn_thread(frequency)
Thread.new(frequency) do |t|
loop do
sleep t
@@mutex.synchronize do
@@pools[frequency].each do |p|
@mutex.synchronize do
@pools[frequency].select!(&:weakref_alive?)
@pools[frequency].each do |p|
p.reap
p.flush
rescue WeakRef::RefError
end
end
end
end
end
end
end

def run
Expand Down

0 comments on commit 1da0e25

Please sign in to comment.