Created
          January 24, 2014 23:45 
        
      - 
      
- 
        Save nyarly/8609200 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | class DeadbeatConnectionRelease | |
| def initialize(app) | |
| @app = app | |
| end | |
| #This is a brittle hack for what appears to be a bug in ActiveRecord 4: | |
| #connections aren't being properly released after their owning threads die | |
| def call(env) | |
| response = @app.call(env) | |
| response[2] = ::Rack::BodyProxy.new(response[2]) do | |
| ActiveRecord::Base.connection_handler.connection_pool_list.each do |pool| | |
| reservers = pool.instance_variable_get("@reserved_connections").keys | |
| deadbeats = reservers - Thread.list.map(&:object_id) | |
| Rails.logger.info{ "Releasing connections held by these no-longer-living Threads: #{deadbeats}" } unless deadbeats.empty? | |
| deadbeats.each do |deadbeat_id| | |
| pool.release_connection(deadbeat_id) | |
| end | |
| end | |
| end | |
| response | |
| rescue | |
| ActiveRecord::Base.clear_active_connections! unless testing | |
| raise | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment