Skip to content

Commit d3b2fcb

Browse files
authored
Merge pull request rails#53748 from byroot/ar-lease-registry-weakmap
Use WeakKeyMap for the connection lease registry
2 parents 19a58ea + bb461f9 commit d3b2fcb

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -117,24 +117,30 @@ def dirties_query_cache
117117
# * private methods that require being called in a +synchronize+ blocks
118118
# are now explicitly documented
119119
class ConnectionPool
120-
class WeakThreadKeyMap # :nodoc:
121-
# FIXME: On 3.3 we could use ObjectSpace::WeakKeyMap
122-
# but it currently cause GC crashes: https://github.com/byroot/rails/pull/3
123-
def initialize
124-
@map = {}
125-
end
126-
127-
def clear
128-
@map.clear
129-
end
120+
# Prior to 3.3.5, WeakKeyMap had a use after free bug
121+
# https://bugs.ruby-lang.org/issues/20688
122+
if ObjectSpace.const_defined?(:WeakKeyMap) && RUBY_VERSION >= "3.3.5"
123+
WeakThreadKeyMap = ObjectSpace::WeakKeyMap
124+
else
125+
class WeakThreadKeyMap # :nodoc:
126+
# FIXME: On 3.3 we could use ObjectSpace::WeakKeyMap
127+
# but it currently cause GC crashes: https://github.com/byroot/rails/pull/3
128+
def initialize
129+
@map = {}
130+
end
131+
132+
def clear
133+
@map.clear
134+
end
130135

131-
def [](key)
132-
@map[key]
133-
end
136+
def [](key)
137+
@map[key]
138+
end
134139

135-
def []=(key, value)
136-
@map.select! { |c, _| c&.alive? }
137-
@map[key] = value
140+
def []=(key, value)
141+
@map.select! { |c, _| c&.alive? }
142+
@map[key] = value
143+
end
138144
end
139145
end
140146

0 commit comments

Comments
 (0)