This seems to be working for us, but I’m wondering what unknown to me
pitfalls I might run into with this approach.
We use this in rails. reset! is called at the end of every request.
Any obvious issues I’m missing here?
class ThreadLocal
class_attribute :store
self.store = {}
class << self
def reset!
self.store.delete(Thread.current.object_id)
end
def ensure_store_id
self.store[Thread.current.object_id] ||= {}
end
def [](key)
ensure_store_id
self.store[Thread.current.object_id][key]
end
def []=(key,value)
ensure_store_id
self.store[Thread.current.object_id][key] = value
end
end
end
Chris
I don’t think Hash is a thread safe class.
Also, why are you implenting a ThreadLocal? Ruby already gives you
ThreadLocals, just get any Thread object and call [] on it, as in :
Thread.current[ :some_name ] = object
Maurcio L.
http://techbot.me/ - http://twitter.com/#!/mauriciojr
2011/10/7 Maurcio L. [email protected]:
I don’t think Hash is a thread safe class.
Also, why are you implenting a ThreadLocal? Ruby already gives you
ThreadLocals, just get any Thread object and call [] on it, as in :
Thread.current[ :some_name ] = object
I avoided it mainly because I keep seeing conflicting reports on
whether it’s a good idea to use it. Rails uses both methods.
activerecord connection pools use a hash with the thread id, a couple
of other places use the builtin thread locals.
Chris
One other thing I wasn’t sure about is how to delete keys from
Thread.current. Set it to nil? The docs don’t say anything about
this. If it works just like a normal hash that would be very bad, as
we would end up with thousands of keys with nil values hanging around.
Chris