12 ms·
I posted this when I hit similar problems and ended up largely isolating them to ActiveRecord. I have a class which I use for doing background processing in Ru
by wheels 16y ago
I posted this when I hit similar problems and ended up largely isolating them to ActiveRecord. I have a class which I use for doing background processing in Ruby:
class Future
def initialize(postprocessor = nil, &finalize)
@postprocessor = postprocessor
@future = Thread.new do
begin
finalize.call
rescue => ex
warn "Exception in background thread: #{ex}"
end
end
end
def method_missing(method, *args, &block)
data.send(method, *args, &block)
end
def to_s
data.to_s
end
private
def data
@data ||= @postprocessor ? @postprocessor.call(@future.value) : @future.value
end
end
However this was causing random 5 second delays in my Rails app -- even if I never called "data" (and hence never joined). I added the postprocessor so that I could pass in a lambda that does all of the ActiveRecord stuff back in the calling thread, which alleviated the problem.
But in contrast to what bensummers said -- this is actually a Rails problem, not a Ruby problem. Ruby's threads suck, but it seems to be ActiveRecord's locking that's at the root of the problem.