Ruby on Rails Thursday, December 22, 2011

On Thu, Dec 22, 2011 at 11:58 AM, Alexey Petrushin <lists@ruby-forum.com> wrote:

Hello, can You please explain to me why we can't use Thread.new in
:after_save?

Let's suppose the following situation: we have a blog and using remote
search engine (in form of http service) to index it. So, after any
change to the blog post we should also make an http call to notify
search service about changes. In the code it will look something like
this:

 class Post < ActiveRecord::Base
   after_save do |model|
     Thread.new do
       # making remote HTTP call.
       remote_search_engine.update model
     end
   end
 end

 class PostController < ActiveController::Base
   def upate
     post = Post.by_id(params[:id])
     post.update_attributes params[:post]
     render json: post
   end
 end

Theoretically it should work. It should update post, immediately return
JSON response,
and finish call to the search engine sometime later
But nobody does this, why?

For a very long time, I thought that nobody using this technique because
this external http call will blocks the whole VM, so it make no sense to
use it.
But a couple days ago I found that this is actually wrong, this http
call will not block the VM (Fibur as a prove
https://gist.github.com/1498215 ).

So, now I wondering - what other problems are out there? Why nobody uses
this and use instead tools like delayed_job and resque?


My guess would be because of the overhead in managing threads.  If your rails code is spawning a new thread after every save, that could get dangerous really quickly.  So then  you would need some kind of thread manager to make sure that threads are properly closing, that threads aren't interfering with each other (what if you save a model twice in quick succession and, for one reason or another, the first thread takes longer to complete so effectively the results of this thread win out in the end), etc? 

 
Thanks!

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment