ThreadLocal-like in Pharo Smalltalk
Asked Answered
C

1

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.

Contrabass answered 27/2, 2017 at 15:17 Comment(0)
E
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.

Ellisellison answered 27/2, 2017 at 15:35 Comment(6)
Sweet! Thanks a lot!Contrabass
Related curiosity: it is strictly necessary to create a subclass or I could use ProcessLocalVariable/DynamicVariable directly?Contrabass
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?Garwood
@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.Contrabass
@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).Ellisellison
Oh! I didn't realize it was a class side variable... Thanks!Contrabass

© 2022 - 2024 — McMap. All rights reserved.