我追查了一個奇怪的錯誤undefined method `run_callbacks' for nil:NilClass
,並能夠用這個示例代碼重現它。處理連接池活動記錄超時的正確方法是什麼?
基本上問題是活動記錄獲取超時(默認值是5秒),但拋出一個未定義的方法異常,這對我來說似乎是錯誤的。
但無論如何,處理這個問題的正確方法是什麼?在我的真實代碼中,我有一大堆忙於做實際工作的線程,但偶爾我遇到了這個錯誤。所以想象一下puts
是真正的代碼。我希望現有的線程在發生這種情況時繼續工作。
threads = []
10.times do |n|
threads << Thread.new {
ActiveRecord::Base.connection_pool.with_connection do |conn|
puts "#{n} #{conn}"
res = conn.execute("select sleep(6)", :async => true)
end
}
end
# block and wait for all threads to finish
threads.each { |t| puts "joined" ; t.join }
rescue Exception => e
puts $!, [email protected]
end
如果我運行此代碼是我得到的異常。如果我把睡眠減少到4秒,我不會。這是6s睡眠的輸出。
joined
0 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c6380>
1 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c5548>
2 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c4fe4>
3 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c4a80>
4 #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0xb73c451c>
joined
joined
joined
joined
joined
undefined method `run_callbacks' for nil:NilClass
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:212:in `checkin'
sqltst.rb:31:in `join'
sqltst.rb:31
sqltst.rb:31:in `each'
sqltst.rb:31
如果您嘗試捕獲線程內的異常,是否會得到相同的錯誤? – 2012-04-10 04:36:32