Skip to content

Instantly share code, notes, and snippets.

@jrochkind
Created December 29, 2016 20:41
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 jrochkind/f5bbe76bcddc5a82f9b4ed96746cfe3e to your computer and use it in GitHub Desktop.
Save jrochkind/f5bbe76bcddc5a82f9b4ed96746cfe3e to your computer and use it in GitHub Desktop.
# an action method in a Rails controller, Rails5
def show
futures = 2.times.collect do |n|
Concurrent::Future.execute do
# NEED to wrap here, in case _any_ autoloading is going to happen,
# need to tell Rails so it can be done thread-safely. Or else we might
# get a deadlock.
Rails.application.executor.wrap do
SomeExpensiveNetworkOrIoWorker.new(n).call
end
end
end
# If any autoloading happened in one or more of those threads, the threads
# might currently not actually be doing anything, they're just blocking waiting
# for access to auto-loading, but this 'main' Rails request/response thread
# may be holding onto the lock, we need to release it to allow the threads to
# get it and do their work -- making sure not to do anything in _this_ thread
# that might trigger an auto-load inside the permit_concurrent_loads block.
ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
@results = futures.collect(&:value)
end
# render response
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment