5

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.

1 Answer 1

8

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.

6
  • Sweet! Thanks a lot!
    – VitorCruz
    Commented Feb 27, 2017 at 21:06
  • Related curiosity: it is strictly necessary to create a subclass or I could use ProcessLocalVariable/DynamicVariable directly?
    – VitorCruz
    Commented Mar 1, 2017 at 3:26
  • The only example I can think of where you might need a variable local to a process (or to a section of it) is a cache: you don't want the cache to be visible outside a specific computation. Do you know of any other cases where this could be useful? Commented Mar 1, 2017 at 11:13
  • @LeandroCaniglia, the Hibernate usage is one. You have a resource that caches during a specific process execution (entity state and queries result) and that provides functionality for users (list, update, delete etc). The alternatives are always clumsy, such as passing the same object everywhere. I don't think there aren't much applications though: it is occasionally useful I think.
    – VitorCruz
    Commented Mar 1, 2017 at 18:42
  • 1
    @VitorCruz, if you do not subclass you will have just one variable available in the whole system, since they are accessible doing "MyVariable value". So I would say yes, you need one subclass for each variable (of course, one variable can be a complex object too, with many attributes).
    – EstebanLM
    Commented Mar 1, 2017 at 19:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.