Skip to content

Instantly share code, notes, and snippets.

@mz026
Last active May 24, 2017 06:57
Show Gist options
  • Save mz026/a8466410b0edbd31346ba6fba6e4ec15 to your computer and use it in GitHub Desktop.
Save mz026/a8466410b0edbd31346ba6fba6e4ec15 to your computer and use it in GitHub Desktop.
test connection pool v.s. thread v.s. `with_connection`
# with pool size = 2
def query thread_idx
p "#{thread_idx}: in thread"
p "#{thread_idx}: conn id: #{ActiveRecord::Base.connection.object_id}"
p "#{thread_idx}: #{User.count}"
puts "#{thread_idx}: finish query"
sleep 0.5
puts "#{thread_idx}: end thread"
end
task :test_conn => :environment do
require 'user'
threads = 3.times.map do |i|
Thread.new(i) do |idx|
# not ok
# query(idx)
# ok
ActiveRecord::Base.connection_pool.with_connection do
query(idx)
end
end
end
threads.each(&:join)
p 'done1'
th = Thread.new do
query('main')
end
th.join
p 'ok!'
end
task :test_conn2 => :environment do
# ref: https://github.com/puma/puma/issues/1004#issuecomment-227242301
# ref: https://github.com/rails/rails/blob/578f2c87d004a0afb1a2fc74c25dc457288c41ac/activerecord/test/cases/reaper_test.rb#L61-L82
pool = ActiveRecord::Base.connection_pool
conn = nil
child = Thread.new do
conn = pool.checkout
Thread.stop
end
while conn.nil?
Thread.pass
end
assert conn.in_use?
child.terminate
while conn.in_use?
Thread.pass
end
# this line will never be reached
assert !conn.in_use?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment