Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Concurrent::Map than Mutex and Mutex_m for statement caches #30069

Merged
merged 1 commit into from
Aug 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 3 additions & 4 deletions activerecord/lib/active_record/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/filters"
require "concurrent/map"

module ActiveRecord
module Core
Expand Down Expand Up @@ -149,7 +150,7 @@ def allocate
end

def initialize_find_by_cache # :nodoc:
@find_by_statement_cache = { true => {}.extend(Mutex_m), false => {}.extend(Mutex_m) }
@find_by_statement_cache = { true => Concurrent::Map.new, false => Concurrent::Map.new }
end

def inherited(child_class) # :nodoc:
Expand Down Expand Up @@ -281,9 +282,7 @@ def type_caster # :nodoc:

def cached_find_by_statement(key, &block)
cache = @find_by_statement_cache[connection.prepared_statements]
cache[key] || cache.synchronize {
cache[key] ||= StatementCache.create(connection, &block)
}
cache.compute_if_absent(key) { StatementCache.create(connection, &block) }
end

def relation
Expand Down
9 changes: 3 additions & 6 deletions activerecord/lib/active_record/reflection.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# frozen_string_literal: true

require "thread"
require "active_support/core_ext/string/filters"
require "active_support/deprecation"
require "concurrent/map"

module ActiveRecord
# = Active Record Reflection
Expand Down Expand Up @@ -443,8 +443,7 @@ def initialize(name, scope, options, active_record)
@type = options[:as] && (options[:foreign_type] || "#{options[:as]}_type")
@foreign_type = options[:foreign_type] || "#{name}_type"
@constructable = calculate_constructable(macro, options)
@association_scope_cache = {}
@scope_lock = Mutex.new
@association_scope_cache = Concurrent::Map.new

if options[:class_name] && options[:class_name].class == Class
ActiveSupport::Deprecation.warn(<<-MSG.squish)
Expand All @@ -463,9 +462,7 @@ def association_scope_cache(conn, owner, &block)
if polymorphic?
key = [key, owner._read_attribute(@foreign_type)]
end
@association_scope_cache[key] ||= @scope_lock.synchronize {
@association_scope_cache[key] ||= StatementCache.create(conn, &block)
}
@association_scope_cache.compute_if_absent(key) { StatementCache.create(conn, &block) }
end

def constructable? # :nodoc:
Expand Down