Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Thread.current values are being kept between requests #8517

Closed
elado opened this Issue · 5 comments

5 participants

@elado

Under servers like thin and `unicorn, threads are managed in a way that the Thread.current keeps its values between requests, unless cleared.

This code in a controller:

before = Thread.current[:x]
Thread.current[:x] = 1
render text: [ before, Thread.current[:x]  ].inspect

when executed twice (even from different sessions), will print nil, 1, and then 1, 1.

I saw that when Rails used Thread.current (e.g. in IdentityMap, Explain) it cleared the value before the request and restored it. If this is necessary all the time, how about clearing Thread.current between requests with a middleware as a part of Rails? Or have some kind of per-request storage for Rails.

Thoughts?

@steveklabnik steveklabnik referenced this issue in drapergem/draper
Closed

Use of Thread.current and ViewContext #390

@seejee

I agree with @elado that it should be the middleware's responsibility to create and destroy a per-request storage object around each request.

This storage object might end up being a thin wrapper around Thread.current, but having it abstracted from any specific threading code will decouple the code that uses it from knowledge of Rails' threading model and make tests running in parallel less susceptible to cross contamination.

@glebm

The way to got about it without breaking stuff is:

  • Clear that variable before request. Clearing it after request is difficult to do cleanly, because exceptions might result in after filter never being triggered
  • Clearing all the variables is a bit dangerous, because Thread.current may be used for keeping permanent per-thread data, such as stats, profiling information, separate log outputs per threads, etc... For a typical Rails application this is probably not an issue, but clearing Thread.current will cause issues when trying to debug local memory leaks and such.
@steveklabnik
Collaborator

@tenderlove is always interested about thread safety issues, so calling him in on this one, too.

@thedarkone

Automatically nuking all of the Thread.current values at the end or beginning of the request should be out of question.

If Rails' usage of Thread.current results in bugs, please open a ticket. Otherwise if your code uses Thread.current and doesn't clean up after itself, you should fix your code.

@steveklabnik
Collaborator

I wrote a gem: https://github.com/steveklabnik/request_store

Since Thread is a Ruby-interpreter thing, and not a Rails thing, this is not a bug, so I'm closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.