Last Updated: February 25, 2016
·
1.992K
· wildtangent

Problems with Thread.current variables not getting unset between requests

A very nasty problem arose for me recently, regarding Thread.current.
I'm using Ruby 1.9.2 and Rails 2.3.8 if it matters.

Now without getting into a flame war about why and why not to use Thread.current, we do, and it's not changing for now.

To cut a long story short, we were finding that variables set in Thread.current[:myvariable] were somehow leaking between different requests. Our suspicion is that Passenger smart-lv2 spawning but we haven't had time to create a simple app to test it on, and it only happens under high concurrency which makes it hard to be sure.

I haven't found out exactly why yet, but the way to fix it is to make sure that any variables set using Thread.current are unset at the start of each new request (or the end of an old one)

e.g.

before_filter :clear_thread_current

def clear_thread_current
  Thread.current[:myvariable] = nil
end

Dirty, probably wrong but it solved my two day old problem instantly.

[EDIT] My colleague, who's known jovially as the "Thread master" says this is technically known as "Thread Local Storage" (TLS). Good to know.