Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadLocal-like in Pharo Smalltalk

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.

like image 807
VitorCruz Avatar asked Feb 27 '17 15:02

VitorCruz


1 Answers

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.

like image 87
EstebanLM Avatar answered Nov 19 '22 10:11

EstebanLM