Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have "thread" local variables in Node?

Tags:

node.js

I would like to store a variable that is shared between all stack frames (top down) in a call chain. Much like ThreadLocal in Java or C#.

I have found https://github.com/othiym23/node-continuation-local-storage but it keeps loosing context for all my use cases and it seems that you have to patch the libraries you are using to make it local-storage-aware which is more or less impossible for our code base.

Are there really not any other options available in Node? Could domains, stacktraces or something like that be used to get a handle (id) to the current call chain. If this is possible I can write my own thread-local implementation.

like image 958
Joppe Avatar asked Feb 26 '16 11:02

Joppe


People also ask

Can threads access local variables?

But: No, threads do not share real local variables.

How do I create a local thread variable?

Creating a ThreadLocal variable The variable of ThreadLocal can be created using the following code: private ThreadLocal threadLocal = new ThreadLocal();

Are local variables shared between threads?

Tip: Unlike class and instance field variables, threads cannot share local variables and parameters. The reason: Local variables and parameters allocate on a thread's method-call stack. As a result, each thread receives its own copy of those variables.

Are static variables ThreadLocal?

static final ThreadLocal variables are thread safe. static makes the ThreadLocal variable available across multiple classes for the respective thread only. it's a kind of Global variable decaration of the respective thread local variables across multiple classes.


1 Answers

Yes, it is possible. Thomas Watson has spoken about it at NodeConf Oslo 2016 in his Instrumenting Node.js in Production (alt.link).

It uses Node.js tracing - AsyncWrap (which should eventually become a well-established part of the public Node API). You can see an example in the open-source Opbeat Node agent or, perhaps even better, check out the talk slides and example code.

like image 149
Jakub Holý Avatar answered Sep 28 '22 11:09

Jakub Holý