For instance, methods such as:
class MyClass
self.perform(id)
hash = doSomething(id)
doMoreStuff(hash)
return hash
end
end
My concern is if I have multiple threads calling MyClass.perform(). Could the object hash be potentially overwritten by another thread? In other words, Thread 1 calls doSomething and gets a hash returned of {1 => 1}. But right afterwards Thread 2 calls doSomething and gets a hash of {2 => 2}. What happens now? Does Thread 1’s hash change to {2 => 2}?
Or does each thread work on its own hash that can never be touched by other threads? Assume doSomething and doMoreStuff are already thread-safe.
If it matters, I am using Rails 3.0.
The local variables, such as your
hash, are local to the particular invocation of the surrounding method. If two threads end up callingperformat the same time, then each call will get its own execution context and those won’t overlap unless there are shared resources involved: instance variables (@hash), class variables (@@hash), globals ($hash), … can cause concurrency problems. There’s nothing to worry about thread-wise with something simple like yourperform.However, if
performwas creating threads and you ended up with closures insideperform, then you could end up with several threads referencing the same local variables captured through the closures. So you do have to be careful about scope issues when you create threads but you don’t have to worry about it when dealing with simple methods that only work with local variables.