Is there an equivalent in Pharo for ThreadLocals of Java, or a way to achieve similar behavior? For example, in Hibernate ThreadLocals are used to provide a thread (current request/context) "scoped" unity of work instance — named Session on Hibernate — through a single getCurrentSession method call. The developer don't need to worry and just believe that the method will return the right unit of work. Is that possible on Pharo?
I skimmed for this on Pharo Books (Pharo by example, Pharo enterprise and Deep Pharo) and in this page, but couldn't find useful information.
in Pharo, you use a subclass of ProcessLocalVariable
.
For example:
"Create a class to store you variable"
ProcessLocalVariable subclass: #MyVariable.
"Use it like this"
MyVariable value: myValue.
"Inside your code, access to current value like this"
MyVariable value.
Notice that even more powerful than thread local variables you have "dynamic variables" which are relative to the execution stack (more precise than threads) You use it like this:
"Create a class to store you variable"
DynamicVariable subclass: #MyVariable.
"Use it like this"
MyVariable
value: myValue
during: [
"... execute your code here... usually a message send"
self doMyCode ].
"Inside your code, access to current value like this"
MyVariable value.
This kind of variables offers same functionality (they are even more powerful) and are usually best replacement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With