Safety and reliability of Thread.current

5 views
Skip to first unread message

Giuseppe

unread,
Oct 27, 2011, 10:30:32 AM10/27/11
to rubyonra...@googlegroups.com
Hello,
getting and setting values in the Thread.current hash appears in the RoR code a bunch of times, including in active_record and active_support.
I keep getting conflicting information, however, on whether information stored in Thread.current is dependable.
In essence, this is my question:

Is the Thread.current hash guaranteed to be available and private throughout one and only one request-response cycle?

In other words, if I do something like:
Thread.current[:my_own_very_special_key] = 1
at the beginning of a response, can I count on all parts of my application, including models(*), to reliably access that value?

Provided I also do:
Thread.current[:my_own_very_special_key] = nil
just before the end of the response (say, in a controller's after_filter), am I guaranteed that the information is not leaked to other processes/threads/requests/browsers/users?

(OK, I have just given out my ignorance of webserver and webapp framework innards. Oh well...)

Thanks!
Giuseppe

(*) I know that accessing Thread.current from my models is frowned upon, but I would very much like to know if the practice is safe, albeit ugly.

Frederick Cheung

unread,
Oct 27, 2011, 12:22:48 PM10/27/11
to Ruby on Rails: Talk


On Oct 27, 3:30 pm, Giuseppe <giuseppe.bert...@gmail.com> wrote:
> Hello,
> getting and setting values in the Thread.current hash appears in the RoR
> code a bunch of times, including in active_record and active_support.
> I keep getting conflicting information, however, on whether information
> stored in Thread.current is dependable.
> In essence, this is my question:
>
> *Is the Thread.current hash guaranteed to be available and private
> throughout one and only one request-response cycle?*
>

I would feel odd about relying on some subsequent request not using
the same thread - using a pool of threads to handle requests seems
entirely reasonable (and a quick experiment implies that thin/sinatra
does this).

Thread.current isn't going to change under your feet though, not
unless you explicitly try and run code in another thread.

Regarding privacy, any other bit of ruby that happens to be running
can list all threads and read/write to their thread local information,
but they're obviously not going to do that for shits and giggles.
Other than picking keys that are unlikely to clash with other stuff I
wouldn't worry about it.

Fred
Reply all
Reply to author
Forward
0 new messages