title: How to manage opening and closing database connections while working with activerecords and multiple threads
body: <p>I am trying to implement a multithreaded method in rails such that I can create/update multiple records very quickly.</p>
  
  <p>This is the outline of my program.</p>
  
  <pre><code>ActiveRecord::Base.transaction do
    (1..10).each do |i|
      arr[i] = Thread.new {
         &lt;some logic on obj&gt;
         ...
         ...
         obj.save! 
      }
    end
    arr.each {|t| t.join}
  end
  </code></pre>
  
  <p>This gives me warnings on my log. </p>
  
  <pre><code>DEPRECATION WARNING: Database connections will not be closed automatically, 
  please close your database connection at the end of the thread by calling `close`
  on your connection.
  </code></pre>
  
  <p>And it gives me an error </p>
  
  <pre><code>could not obtain a database connection within 5 seconds (waited 5.059358 seconds). 
  The max pool size is currently 5; consider increasing it.
  </code></pre>
  
  <p>I tried:
   - changing database.yaml and increasing the poolsize and timeout there. 
   - modified the existing code in the following way.</p>
  
  <pre><code>   ActiveRecord::Base.connection_pool.clear_stale_cached_connections!
     begin
       ActiveRecord::Base.transaction do
          (1..10).each do |i|
            arr[i] = Thread.new {
               &lt;some logic on obj&gt;
               ...
               ...
               obj.save!
               ActiveRecord::Base.connection.close 
            }
          end
          arr.each {|t| t.join}
       end
     ensure
       ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
       ActiveRecord::Base.clear_active_connections!
     end
  </code></pre>
  
  <p>I am still getting the same warning and error.
  I am obviously missing the concept here. How do I proceed with this?</p>