Skip to content

Instantly share code, notes, and snippets.

@meetme2meat
Last active May 18, 2018 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meetme2meat/541e46deeb496bf475691e7c5288fedb to your computer and use it in GitHub Desktop.
Save meetme2meat/541e46deeb496bf475691e7c5288fedb to your computer and use it in GitHub Desktop.
### A quick dirty fix.
## Current version ActiveRecord 4.2.0
## Jruby 9.0.5.0
## Avoid some Mutex lock. Reference issue -> https://github.com/rails/rails/pull/14938.
## Why we need this.
## Since we cant upgrade to 5.2.stable because the JDBC driver support are still not mature and the 5.0.x is causing some strange
## error (which I seem is fixed only in 5.2.stable)
class Handler
attr_accessor :conn
def initialize
end
def start
begin
## May be timeout in checkout process can help avoid the mutex hold propogating to all thread waiting to checkout a connection.
Timeout::timeout(0.3) do
## activeRecord connection pool size is n
## connect_timeout : 0.25
self.conn = ActiveRecord::Base.connection_pool.checkout
## there can be a slight a slight problem,where connection can become orphan i.e the driver created a connection but before
## self.conn was set the timeout happened.
end
rescue Timeout::Error
logger.error "Bail out"
end
## get reserved connection
reserved_connection = ActiveRecord::Base.connection_pool.instance_variable_get(:'@reserved_connections')
reserved_connection[Thread.current.object_id] ||= conn
## do stuff A with DB
## do stuff B with DB
ensure
release_connection if self.conn
end
def release_connection
ActiveRecord::Base.connection_pool.checkin(conn)
end
end
class Puller
def start
loop do
## A Celluloid Actor ThreadPool of size n
ThreadPool.schedule {
Handler.new().start
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment