rails/rails — pull request #14151 by mhfs (2014-02-21 22:11:48+00:00)
Title: Do not rely on Hash#each_value as it blocks Hash[]= 

... and causes exceptions in threaded environments.

Attempt to fix #10695 based on how Rails 4 handles it now: https://github.com/rails/rails/blob/4-0-stable/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb#L501

In my case the problem is between these two methods competing for `@connection_pools`

```ruby
def establish_connection(name, spec)
@connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec)
@class_to_pool[name] = @connection_pools[spec]
end

def clear_active_connections!
@connection_pools.values.each {|pool| pool.release_connection }
end
```

Would love some guidance on how to write a proper test for this. I haven't been able to reproduce outside a high concurrent threaded environment. Standalone script here: https://github.com/mhfs/sidekiq-dbcharmer-ar-bug

Tests pass as is.

Involved people:
@mperham @dashbitla @steveklabnik @thedarkone @kovyrin

How I got to the issue:
https://github.com/kovyrin/db-charmer/issues/90
https://github.com/rails/rails/issues/10695

Error and backtrace:
```
RuntimeError: can't add a new key into hash during iteration
/vendor/ruby/2.0.0/gems/activerecord-3.2.17/lib/active_record/connection_adapters/abstract/connection_pool.rb:375 in "[]="
/vendor/ruby/2.0.0/gems/activerecord-3.2.17/lib/active_record/connection_adapters/abstract/connection_pool.rb:375 in "establish_connection"
/vendor/ruby/2.0.0/gems/activerecord-3.2.17/lib/active_record/connection_adapters/abstract/connection_specification.rb:137 in "establish_connection"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/active_record/connection_switching.rb:25 in "establish_real_connection_if_exists"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/connection_factory.rb:51 in "generate_abstract_class"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/connection_factory.rb:35 in "establish_connection"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/connection_factory.rb:24 in "connect"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/active_record/connection_switching.rb:66 in "coerce_to_connection_proxy"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/active_record/connection_switching.rb:82 in "switch_connection_to"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/active_record/multi_db_proxy.rb:39 in "on_db"
/vendor/ruby/2.0.0/gems/db-charmer-1.9.0/lib/db_charmer/active_record/multi_db_proxy.rb:19 in "method_missing"
/app/jobs/backfill_stats_job.rb:7 in "perform"
```