Reputation: 10350
I have heard this comments many times and understand the importance to kill a thread local before it gets reused:
"Not cleaning up thread-locals might be an issue if your framework reuses threads".
In the following example, it is straightforward to tell when the thread local should be killed:
def do_with_current_user
Thread.current[:current_user] = self.current_user
begin
yield
ensure
Thread.current[:current_user] = nil
end
end
In Rails debugger, I see a Thread.current
stay alive after a few actions and loading models/routes (there is no thread local killing mechanism in place in the app). My question is how Ruby/Rails determines when to kill a thread local.
Upvotes: 2
Views: 757
Reputation: 211560
I think the problem is Rails doesn't determine when to kill thread local variables so you might end up with a serious mess if them if you don't have code like this to automatically remove them. I try to stay away from them whenever possible, but there are cases when they cannot be avoided.
In those situations, avoid leaving any trace of them behind. Clutter in the thread local variable department can cause huge headaches as those objects cannot be garbage collected.
Your code can be simplified, too:
def do_with_current_user
Thread.current[:current_user] = self.current_user
yield
ensure
Thread.current[:current_user] = nil
end
You may want to introduce a wrapper as well:
def current_user_local
Thread.current[:current_user] || self.current_user
end
That way in your code it's not obvious you're using thread-local variables and if you ever change your mind about how that information is stored, you don't have to go and track down instances of Thread.current
and replace them.
Upvotes: 2